diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb88306..bd3104c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -222,6 +222,11 @@ jobs: LQ_ORA_PASSWORD: lowquery steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Go driver tests against a real server + run: go test -count=1 -v ./internal/drivers/oracle/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -271,6 +276,11 @@ jobs: LQ_MYSQL_ENGINE: ${{ matrix.engine }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Go driver tests against a real server + run: go test -count=1 -v ./internal/drivers/mysql/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -308,6 +318,11 @@ jobs: LQ_MSSQL_DB: master steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Go driver tests against a real server + run: go test -count=1 -v ./internal/drivers/sqlserver/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -344,6 +359,11 @@ jobs: LQ_REDIS_PORT: "6379" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Go driver tests against a real server + run: go test -count=1 -v ./internal/drivers/redis/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -383,6 +403,11 @@ jobs: LQ_CASSANDRA_PORT: "9042" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Go driver tests against a real server + run: go test -count=1 -v ./internal/drivers/cassandra/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: diff --git a/go.mod b/go.mod index f4699ec..6cb8533 100644 --- a/go.mod +++ b/go.mod @@ -3,24 +3,37 @@ module github.com/LowBloat/LowQuery go 1.26.4 require ( + github.com/apache/cassandra-gocql-driver/v2 v2.2.0 github.com/danieljoos/wincred v1.2.3 + github.com/go-sql-driver/mysql v1.11.0 + github.com/golang-sql/sqlexp v0.1.0 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.13.0 + github.com/microsoft/go-mssqldb v1.12.0 github.com/ncruces/go-sqlite3 v0.38.2 + github.com/redis/go-redis/v9 v9.24.1 + github.com/sijms/go-ora/v2 v2.9.0 github.com/wailsapp/wails/v3 v3.1.0 github.com/zalando/go-keyring v0.2.8 golang.org/x/sys v0.50.0 ) require ( + filippo.io/edwards25519 v1.2.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect 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/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // 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 + github.com/shopspring/decimal v1.4.0 // indirect + go.uber.org/atomic v1.12.0 // indirect + golang.org/x/crypto v0.59.0 // indirect + golang.org/x/term v0.48.0 // indirect golang.org/x/text v0.44.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect ) diff --git a/go.sum b/go.sum index b41f206..4b9f54c 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +1,46 @@ +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0 h1:MaKvxE6D0KkjOg6Wd9M00iqP5PR0kUxCfiezes4JweM= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0/go.mod h1:i2h9fsTFKZorh8RdV2IcSUf/Qj98GlTkrTvUbX/s8as= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0/go.mod h1:ucUjca2JtSZboY8IoUqyQyuuXvwbMBVwFOm0vdQPNhA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 h1:Nljr4q1GRA/5vCrMONS+g4u4LRHNgOXVSh3O43J2CnI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI= +github.com/apache/cassandra-gocql-driver/v2 v2.2.0 h1:t/tcCpYdBQuyPy0E52SNsyKRG/61Pv2V8+429gKYKzw= +github.com/apache/cassandra-gocql-driver/v2 v2.2.0/go.mod h1:YrDMQWYKILVs27u3u0VOdOqssyx5FnIaVEisehz7KL8= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 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/go-sql-driver/mysql v1.11.0 h1:0dFnuu2mR7g+8Smo/rL18y1WnTLgVrHttzSahf20Gb4= +github.com/go-sql-driver/mysql v1.11.0/go.mod h1:evJsoGjlO/9BFsnfXyjtluDYb3OSGzPNOnUaBl/2Dao= 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/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= +github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 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= @@ -21,35 +51,72 @@ 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/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/microsoft/go-mssqldb v1.12.0 h1:Jwg/8jz2MKlFOYf4Oj7wMOQuTpCLrP4PIx0aINasMfw= +github.com/microsoft/go-mssqldb v1.12.0/go.mod h1:iYsISdcqI4Tf8x/JwwkHfBu5pxtSD6lSJB8tCrOoo6E= 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/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk= +github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.24.1 h1:WZ9a1QO2mkLFLYyQ1IPFvS4xBuCuZy9eXtIxppdj/Z0= +github.com/redis/go-redis/v9 v9.24.1/go.mod h1:ted97kpLnB4S2KJkTkw+7GzRjgkFnU909IIrksu+ut4= +github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= +github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sijms/go-ora/v2 v2.9.0 h1:+iQbUeTeCOFMb5BsOMgUhV8KWyrv9yjKpcK4x7+MFrg= +github.com/sijms/go-ora/v2 v2.9.0/go.mod h1:QgFInVi3ZWyqAiJwzBQA+nbKYKH77tdp1PYoCqhR2dU= 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/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= 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= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= 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/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= 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/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 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/commands.go b/internal/app/commands.go index 2d38229..4c02ed9 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -6,6 +6,7 @@ import ( "os" "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers/oracle" "github.com/LowBloat/LowQuery/internal/model" "github.com/LowBloat/LowQuery/internal/textcodec" ) @@ -167,6 +168,14 @@ func (a *App) commands() map[string]handler { }), // Host services the Tauri plugins used to provide. + "oracle_tns_sources": command(func(ctx context.Context, _ none) ([]oracle.TNSSource, error) { + return oracle.TNSSources(), nil + }), + "oracle_tns_folder": command(func(ctx context.Context, p struct { + Path string `json:"path"` + }) (*oracle.TNSSource, error) { + return oracle.TNSFolder(p.Path) + }), "app_version": command(func(ctx context.Context, _ none) (string, error) { return a.version, nil }), diff --git a/internal/app/engines.go b/internal/app/engines.go index 60796f7..2edfa8f 100644 --- a/internal/app/engines.go +++ b/internal/app/engines.go @@ -5,18 +5,42 @@ import ( "github.com/LowBloat/LowQuery/internal/apperr" "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/cassandra" + "github.com/LowBloat/LowQuery/internal/drivers/mysql" + "github.com/LowBloat/LowQuery/internal/drivers/oracle" "github.com/LowBloat/LowQuery/internal/drivers/postgres" + "github.com/LowBloat/LowQuery/internal/drivers/redis" "github.com/LowBloat/LowQuery/internal/drivers/sqlite" + "github.com/LowBloat/LowQuery/internal/drivers/sqlserver" "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) { + // Each case returns through a typed variable so a nil *Session never + // becomes a non-nil interface. switch p.Engine { case model.Postgres: - return postgres.Connect(ctx, p, password) + return wrap(postgres.Connect(ctx, p, password)) case model.SQLite: - return sqlite.Connect(ctx, p) + return wrap(sqlite.Connect(ctx, p)) + case model.Oracle: + return wrap(oracle.Connect(ctx, p, password)) + case model.MySQL, model.MariaDB: + return wrap(mysql.Connect(ctx, p, password)) + case model.SQLServer: + return wrap(sqlserver.Connect(ctx, p, password)) + case model.Redis: + return wrap(redis.Connect(ctx, p, password)) + case model.Cassandra: + return wrap(cassandra.Connect(ctx, p, password)) } return nil, apperr.Newf(apperr.Invalid, "This build of LowQuery does not connect to %s yet.", p.Engine) } + +func wrap[S drivers.Session](s S, err error) (drivers.Session, error) { + if err != nil { + return nil, err + } + return s, nil +} diff --git a/internal/drivers/cassandra/cassandra.go b/internal/drivers/cassandra/cassandra.go new file mode 100644 index 0000000..6daf1b5 --- /dev/null +++ b/internal/drivers/cassandra/cassandra.go @@ -0,0 +1,1015 @@ +// Package cassandra is the Apache Cassandra session, over the native CQL +// protocol through gocql (Apache Cassandra 3.x, 4.x and 5.x). +// +// - Every statement is sent unprepared as text, like cqlsh does. Rows are +// read with paging: the page size comes from the row limit and reading +// stops at maxRows + 1, so a SELECT on a big table never streams +// everything to show a few rows. +// - Values keep their exact CQL text (varint and decimal keep every digit, +// floats are shortest round-trip, blobs are 0x...). Collections, tuples, +// UDTs and vectors are written as valid CQL literals, so a cell can be +// pasted into an INSERT or UPDATE as it is (values.go). +// - There are no transactions: the session is always in autocommit mode +// and BEGIN BATCH ... APPLY BATCH is just one statement. Saving edits from +// the grid sends one logged batch. +// - CQL has no server-side cancel. Cancel stops waiting, so the interface +// gets its answer at once, but the coordinator keeps working until its +// own request timeout. +// - Server warnings (tombstone thresholds, large batches, aggregations +// without a partition key) arrive as messages, like PostgreSQL notices. +// - Requests run at consistency LOCAL_ONE, the cqlsh default. With the +// local datacenter set, only its nodes get requests. +// - USE cannot run on a pool of connections, so the session reconnects +// with the new keyspace instead. +// - The schema comes from system_schema (and system_virtual_schema for the +// virtual keyspaces of 4.0+), which every 3.0+ server has. DESCRIBE is a +// cqlsh command, not part of the protocol, so the CREATE statements are +// built from the catalog (ddl.go). +package cassandra + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "slices" + "sort" + "strings" + "sync" + "time" + + gocql "github.com/apache/cassandra-gocql-driver/v2" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + defaultPort = 9042 + connectTimeout = 10 * time.Second + // preferTLSTimeout bounds the TLS attempt of prefer: a server without + // TLS gives up early and the session falls back to plain TCP. + preferTLSTimeout = 8 * time.Second + // pageCap is the largest page asked for in one request. + pageCap = 5000 + // catalogPage is the page size of the catalog queries. + catalogPage = 1000 + binaryPreviewBytes = 32 * 1024 +) + +// unprepared goes in front of every statement: gocql prepares SELECT, +// INSERT, UPDATE, DELETE and BATCH statements, judging by their first word, +// and a comment there makes it send them as text instead. Syntax error +// columns are moved back over it (errors.go). +const unprepared = "/**/" + +// Keyspaces that belong to the server, listed after the user's. +var systemKeyspaces = []string{ + "system", + "system_schema", + "system_auth", + "system_distributed", + "system_traces", + "system_views", + "system_virtual_schema", +} + +var virtualKeyspaces = []string{"system_views", "system_virtual_schema"} + +const noTransactions = "Cassandra has no transactions: every statement commits on its own." + +// Session is one Cassandra cluster connection (gocql keeps a pool per node). +type Session struct { + // lock serializes every call except Cancel. + lock chan struct{} + // stop interrupts the running call (Cancel). + stopMu sync.Mutex + stop context.CancelFunc + + opts options + cql *gocql.Session + // Key information per table, for result editing. Cleared by any + // statement that is not a SELECT. + tables map[[2]string]*tableMeta + + serverVersion string + currentUser *string + + schemaMu sync.Mutex + currentSchema *string +} + +var _ drivers.Session = (*Session)(nil) + +// options is what a cluster connection is built from, kept for USE. +type options struct { + hosts []string + user string + password string + datacenter string + tls *tls.Config +} + +// Connect opens a session. password nil means none. +func Connect(ctx context.Context, p model.ConnectionProfile, password *string) (*Session, error) { + port := p.Port + if port == 0 { + port = defaultPort + } + var hosts []string + for _, h := range strings.Split(p.Host, ",") { + if h = strings.TrimSpace(h); h != "" { + hosts = append(hosts, contactPoint(h, port)) + } + } + if len(hosts) == 0 { + return nil, apperr.Invalidf("Enter at least one contact point.") + } + opts := options{ + hosts: hosts, + user: strings.TrimSpace(p.User), + datacenter: strings.TrimSpace(p.Datacenter), + } + if password != nil { + opts.password = *password + } + keyspace := strings.TrimSpace(p.Database) + + var cql *gocql.Session + var err error + switch p.SslMode { + case model.SslDisable: + cql, err = open(ctx, opts, keyspace, 0) + case model.SslRequire, model.SslVerifyFull: + opts.tls = tlsConfig(p.SslMode) + cql, err = open(ctx, opts, keyspace, 0) + default: + withTLS := opts + withTLS.tls = tlsConfig(model.SslPrefer) + cql, err = open(ctx, withTLS, keyspace, preferTLSTimeout) + switch { + case err == nil: + opts = withTLS + case ctx.Err() != nil || isAuthText(err.Error()): + default: + cql, err = open(ctx, opts, keyspace, 0) + } + } + if err != nil { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + var e *apperr.Error + if errors.As(err, &e) { + return nil, e + } + return nil, connectError(err) + } + + s := &Session{ + lock: make(chan struct{}, 1), + opts: opts, + cql: cql, + tables: map[[2]string]*tableMeta{}, + serverVersion: "Apache Cassandra", + } + if keyspace != "" { + s.currentSchema = &keyspace + } + if opts.user != "" { + s.currentUser = model.Str(opts.user) + } + if f, err := s.fetch(ctx, "SELECT release_version FROM system.local"); err == nil && len(f.rows) > 0 { + if v, ok := f.text(f.rows[0], "release_version"); ok { + s.serverVersion = "Apache Cassandra " + v + } + } + return s, nil +} + +// contactPoint is host or host:port as the driver wants it; a bare IPv6 +// address is bracketed. +func contactPoint(host string, defaultPort uint16) string { + port := fmt.Sprint(defaultPort) + if strings.HasPrefix(host, "[") { + if strings.Contains(host, "]:") { + return host + } + return host + ":" + port + } + switch strings.Count(host, ":") { + case 0: + return host + ":" + port + case 1: + return host + } + return "[" + host + "]:" + port +} + +// cluster builds the driver configuration. Each session needs its own: a +// host selection policy cannot be shared. +func (o options) cluster(keyspace string) *gocql.ClusterConfig { + c := gocql.NewCluster(o.hosts...) + c.Keyspace = keyspace + c.Consistency = gocql.LocalOne + c.ConnectTimeout = connectTimeout + // The server's own timeouts apply; Cancel stops waiting. + c.Timeout = 0 + c.WriteTimeout = connectTimeout + c.Metadata.CacheMode = gocql.Disabled + if o.datacenter != "" { + // Requests go to the local datacenter only. + c.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy(o.datacenter) + c.HostFilter = gocql.DataCenterHostFilter(o.datacenter) + } else { + c.PoolConfig.HostSelectionPolicy = gocql.RoundRobinHostPolicy() + } + if o.user != "" { + c.Authenticator = gocql.PasswordAuthenticator{Username: o.user, Password: o.password} + } + if o.tls != nil { + c.SslOpts = &gocql.SslOptions{Config: o.tls} + } + return c +} + +var errTLSTimeout = errors.New("the TLS connection did not answer in time") + +// open creates a driver session; limit > 0 bounds the wait. A session that +// arrives after the caller gave up is closed. +func open(ctx context.Context, o options, keyspace string, limit time.Duration) (*gocql.Session, error) { + type outcome struct { + s *gocql.Session + err error + } + cfg := o.cluster(keyspace) + done := make(chan outcome, 1) + go func() { + s, err := cfg.CreateSession() + done <- outcome{s, err} + }() + var timeout <-chan time.Time + if limit > 0 { + t := time.NewTimer(limit) + defer t.Stop() + timeout = t.C + } + abandon := func() { + go func() { + if out := <-done; out.s != nil { + out.s.Close() + } + }() + } + select { + case out := <-done: + if out.err != nil && errors.Is(out.err, gocql.ErrNoConnectionsStarted) && o.datacenter != "" { + return nil, apperr.New(apperr.Connection, noNodeMessage) + } + return out.s, out.err + case <-ctx.Done(): + abandon() + return nil, apperr.CancelledErr() + case <-timeout: + abandon() + return nil, errTLSTimeout + } +} + +// tlsConfig: prefer and require encrypt without validating the certificate, +// as everywhere else in the app. verify-full validates the chain, expiry and +// signatures against the system roots but not the host name: the driver +// connects to the addresses the cluster reports (system.peers), which +// certificates rarely list. +func tlsConfig(mode model.SslMode) *tls.Config { + cfg := &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} + if mode == model.SslVerifyFull { + cfg.VerifyPeerCertificate = verifyChain + } + return cfg +} + +func verifyChain(raw [][]byte, _ [][]*x509.Certificate) error { + if len(raw) == 0 { + return errors.New("the server sent no certificate") + } + certs := make([]*x509.Certificate, len(raw)) + for i, r := range raw { + c, err := x509.ParseCertificate(r) + if err != nil { + return err + } + certs[i] = c + } + intermediates := x509.NewCertPool() + for _, c := range certs[1:] { + intermediates.AddCert(c) + } + _, err := certs[0].Verify(x509.VerifyOptions{ + Intermediates: intermediates, + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + }) + return err +} + +func (s *Session) Engine() model.Engine { return model.Cassandra } +func (s *Session) ServerVersion() string { return s.serverVersion } +func (s *Session) CurrentUser() *string { return s.currentUser } + +func (s *Session) CurrentSchema() *string { + s.schemaMu.Lock() + defer s.schemaMu.Unlock() + return s.currentSchema +} + +func (s *Session) TxState() model.TxState { + return model.TxState{Autocommit: true} +} + +// legacy is Cassandra 3.x, whose table options differ from 4.0 and later. +func (s *Session) legacy() bool { + return strings.HasPrefix(s.serverVersion, "Apache Cassandra 3.") +} + +// acquire takes the session lock and returns the context of the call, +// which Cancel or ctx stop. release clears both. +func (s *Session) acquire(ctx context.Context) (context.Context, func(), error) { + if ctx.Err() != nil { + return nil, nil, apperr.CancelledErr() + } + select { + case s.lock <- struct{}{}: + case <-ctx.Done(): + return nil, nil, apperr.CancelledErr() + } + if s.cql == nil { + <-s.lock + return nil, nil, apperr.Connectionf("The connection is closed.") + } + opCtx, cancel := context.WithCancel(ctx) + s.stopMu.Lock() + s.stop = cancel + s.stopMu.Unlock() + return opCtx, func() { + s.stopMu.Lock() + s.stop = nil + s.stopMu.Unlock() + cancel() + <-s.lock + }, nil +} + +// fail maps an error of a call made with ctx; a stopped call is cancelled. +func fail(ctx context.Context, err error, sql string) error { + if ctx.Err() != nil { + return apperr.CancelledErr() + } + return mapError(err, sql) +} + +// Cancel stops waiting for the running call, if any. CQL cannot ask the +// server to stop a request: the coordinator finishes (or times out) on its +// own. +func (s *Session) Cancel(context.Context) error { + s.stopMu.Lock() + defer s.stopMu.Unlock() + if s.stop != nil { + s.stop() + } + return nil +} + +// Close stops the running call, if any, and closes the connections. +func (s *Session) Close() error { + _ = s.Cancel(context.Background()) + s.lock <- struct{}{} + defer func() { <-s.lock }() + if s.cql != nil { + s.cql.Close() + s.cql = nil + } + return nil +} + +func (s *Session) SetAutocommit(_ context.Context, on bool) (model.TxState, error) { + if on { + return s.TxState(), nil + } + return s.TxState(), apperr.Invalidf(noTransactions) +} + +func (s *Session) EndTransaction(context.Context, bool) (model.TxState, error) { + return s.TxState(), apperr.Invalidf(noTransactions) +} + +// query is a statement sent as text at LOCAL_ONE. +func (s *Session) query(sql string) *gocql.Query { + return s.cql.Query(unprepared + sql).Consistency(gocql.LocalOne) +} + +// fetched holds the rows of a catalog query, as raw values. +type fetched struct { + names []string + types []*ctype + rows [][][]byte +} + +func (f *fetched) index(name string) int { + return slices.Index(f.names, name) +} + +// get returns a column's type and value; false when the column is missing +// or null. +func (f *fetched) get(row [][]byte, name string) (*ctype, []byte, bool) { + i := f.index(name) + if i < 0 || i >= len(row) || row[i] == nil { + return nil, nil, false + } + return f.types[i], row[i], true +} + +func (f *fetched) text(row [][]byte, name string) (string, bool) { + t, v, ok := f.get(row, name) + if !ok || !isText(t) { + return "", false + } + return string(v), true +} + +func (f *fetched) boolean(row [][]byte, name string) bool { + t, v, ok := f.get(row, name) + return ok && t.kind == gocql.TypeBoolean && len(v) == 1 && v[0] != 0 +} + +func (f *fetched) integer(row [][]byte, name string) int32 { + t, v, ok := f.get(row, name) + if !ok || t.kind != gocql.TypeInt || len(v) != 4 { + return 0 + } + return int32(uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3])) +} + +// textList reads a list or set of text; anything else is empty. +func (f *fetched) textList(row [][]byte, name string) []string { + t, v, ok := f.get(row, name) + if !ok || (t.kind != gocql.TypeList && t.kind != gocql.TypeSet) || !isText(t.elems[0]) { + return nil + } + r := &reader{data: v} + n := r.int32() + var out []string + for i := 0; i < int(n) && !r.bad; i++ { + if item := r.bytes(); item != nil && !r.bad { + out = append(out, string(item)) + } + } + return out +} + +// textMap reads a map of text to text, in the server's order. +func (f *fetched) textMap(row [][]byte, name string) [][2]string { + t, v, ok := f.get(row, name) + if !ok || t.kind != gocql.TypeMap || !isText(t.elems[0]) || !isText(t.elems[1]) { + return nil + } + r := &reader{data: v} + n := r.int32() + var out [][2]string + for i := 0; i < int(n) && !r.bad; i++ { + k, val := r.bytes(), r.bytes() + if k != nil && val != nil && !r.bad { + out = append(out, [2]string{string(k), string(val)}) + } + } + return out +} + +// literalOf is a column's value as a CQL literal; false when missing or +// null. +func (f *fetched) literalOf(row [][]byte, name string) (string, bool) { + t, v, ok := f.get(row, name) + if !ok { + return "", false + } + s, err := literal(t, v) + return s, err == nil +} + +// fetch runs a catalog statement and reads every page. +func (s *Session) fetch(ctx context.Context, sql string) (*fetched, error) { + f := &fetched{} + var state []byte + for { + iter := s.query(sql).PageSize(catalogPage).PageState(state).IterContext(ctx) + cols := iter.Columns() + if f.names == nil && len(cols) > 0 { + for _, c := range cols { + f.names = append(f.names, c.Name) + } + } + if len(cols) > 0 { + r := newRowReader(cols) + f.types = r.types + for iter.Scan(r.dest...) { + f.rows = append(f.rows, r.values(true)) + } + } + next := iter.PageState() + if err := iter.Close(); err != nil { + return nil, fail(ctx, err, "") + } + if len(cols) == 0 { + return nil, apperr.Internalf("The catalog statement returned no rows.") + } + if len(next) == 0 { + return f, nil + } + state = next + } +} + +// lit is a name a catalog query matches on, as a CQL string literal. +func lit(s string) string { return quoteStr(s) } + +func isVirtual(keyspace string) bool { return slices.Contains(virtualKeyspaces, keyspace) } + +func isSystem(keyspace string) bool { + return slices.Contains(systemKeyspaces, keyspace) || strings.HasPrefix(keyspace, "system_") +} + +// resultColumn is one result column: what the editor needs to know about +// its origin. +type resultColumn struct { + name, keyspace, table string +} + +type tableMeta struct { + columns []model.DbColumn + view bool +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + return s.run(opCtx, req.SQL, req.MaxRows) +} + +func (s *Session) run(ctx context.Context, sql string, limit int) (*model.ExecResult, error) { + started := time.Now() + limit = max(limit, 0) + first := drivers.FirstKeywords(sql, 1) + if len(first) == 1 && first[0] == "USE" { + if keyspace, ok := useTarget(sql); ok { + if err := s.use(ctx, keyspace); err != nil { + return nil, err + } + result := &model.ExecResult{ElapsedMs: uint64(time.Since(started).Milliseconds())} + result.Normalize() + return result, nil + } + } + + result := &model.ExecResult{} + var columns []model.ColumnInfo + var origins []resultColumn + var rows []model.Row + var state []byte + limitBytes := drivers.BinaryLimit(ctx, binaryPreviewBytes) + for { + size := pageCap + if limit > 0 { + size = min(max(limit+1-min(len(rows), limit+1), 1), pageCap) + } + iter := s.query(sql).PageSize(size).PageState(state).IterContext(ctx) + cols := iter.Columns() + var decodeErr error + if len(cols) > 0 { + r := newRowReader(cols) + if columns == nil { + for i, c := range cols { + columns = append(columns, model.ColumnInfo{ + Name: c.Name, + TypeName: typeName(r.types[i]), + Kind: columnKind(r.types[i]), + }) + origins = append(origins, resultColumn{name: c.Name, keyspace: c.Keyspace, table: c.Table}) + } + } + for decodeErr == nil && iter.Scan(r.dest...) { + values := r.values(false) + row := make(model.Row, len(values)) + for i, v := range values { + if row[i], decodeErr = cellText(r.types[i], v, limitBytes); decodeErr != nil { + break + } + } + rows = append(rows, row) + } + } + for _, w := range iter.Warnings() { + result.Notices = append(result.Notices, "WARNING: "+w) + } + next := iter.PageState() + if err := iter.Close(); err != nil { + return nil, fail(ctx, err, sql) + } + if decodeErr != nil { + return nil, decodeErr + } + if len(cols) == 0 || (limit > 0 && len(rows) > limit) || len(next) == 0 { + break + } + state = next + } + if limit > 0 && len(rows) > limit { + rows = rows[:limit] + result.Truncated = true + } + + isSelect := len(first) == 1 && first[0] == "SELECT" + if !isSelect { + clear(s.tables) + } + if columns != nil { + var reason string + result.Editable, reason = s.editable(ctx, sql, isSelect, origins) + if reason != "" { + result.ReadOnlyReason = &reason + } + result.Columns = columns + result.Rows = rows + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.Normalize() + return result, nil +} + +// useTarget reads the keyspace of USE ks / USE "Ks": unquoted names are +// lowercase. +func useTarget(sql string) (string, bool) { + i := skipSpace(sql, 0) + if i+3 > len(sql) || !strings.EqualFold(sql[i:i+3], "USE") { + return "", false + } + i = skipSpace(sql, i+3) + var name string + switch { + case i < len(sql) && sql[i] == '"': + var b strings.Builder + i++ + for { + if i >= len(sql) { + return "", false + } + if sql[i] == '"' { + if i+1 < len(sql) && sql[i+1] == '"' { + b.WriteByte('"') + i += 2 + continue + } + i++ + break + } + b.WriteByte(sql[i]) + i++ + } + name = b.String() + default: + start := i + for i < len(sql) && (isWordByte(sql[i])) { + i++ + } + name = strings.ToLower(sql[start:i]) + } + if name == "" { + return "", false + } + for { + i = skipSpace(sql, i) + if i < len(sql) && sql[i] == ';' { + i++ + continue + } + break + } + return name, i == len(sql) +} + +func isWordByte(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' +} + +// skipSpace skips whitespace and comments from i. +func skipSpace(sql string, i int) int { + for i < len(sql) { + switch { + case sql[i] == ' ' || sql[i] == '\t' || sql[i] == '\n' || sql[i] == '\r' || sql[i] == '\f': + i++ + case strings.HasPrefix(sql[i:], "--") || strings.HasPrefix(sql[i:], "//"): + for i < len(sql) && sql[i] != '\n' { + i++ + } + case strings.HasPrefix(sql[i:], "/*"): + end := strings.Index(sql[i+2:], "*/") + if end < 0 { + return len(sql) + } + i += 2 + end + 2 + default: + return i + } + } + return i +} + +// use switches the session to another keyspace. A USE sent to the server +// would only change the one pooled connection that ran it, so the session +// reconnects with the keyspace instead. +func (s *Session) use(ctx context.Context, keyspace string) error { + found := false + for _, catalog := range []string{"system_schema", "system_virtual_schema"} { + f, err := s.fetch(ctx, "SELECT keyspace_name FROM "+catalog+".keyspaces WHERE keyspace_name = "+lit(keyspace)) + if err != nil { + if catalog == "system_schema" { + return err + } + // Virtual keyspaces exist from Cassandra 4.0. + continue + } + if len(f.rows) > 0 { + found = true + break + } + } + if !found { + e := apperr.Newf(apperr.Database, "Keyspace '%s' does not exist", keyspace) + e.Code = "Invalid" + return e + } + cql, err := open(ctx, s.opts, keyspace, 0) + if err != nil { + if ctx.Err() != nil { + return apperr.CancelledErr() + } + var e *apperr.Error + if errors.As(err, &e) { + return e + } + return connectError(err) + } + s.cql.Close() + s.cql = cql + clear(s.tables) + s.schemaMu.Lock() + s.currentSchema = &keyspace + s.schemaMu.Unlock() + return nil +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + f, err := s.fetch(opCtx, "SELECT keyspace_name FROM system_schema.keyspaces") + if err != nil { + return nil, err + } + var names []string + for _, r := range f.rows { + if n, ok := f.text(r, "keyspace_name"); ok { + names = append(names, n) + } + } + // Virtual keyspaces exist from Cassandra 4.0. + if f, err := s.fetch(opCtx, "SELECT keyspace_name FROM system_virtual_schema.keyspaces"); err == nil { + for _, r := range f.rows { + if n, ok := f.text(r, "keyspace_name"); ok { + names = append(names, n) + } + } + } else if opCtx.Err() != nil { + return nil, apperr.CancelledErr() + } + sort.Strings(names) + names = slices.Compact(names) + sort.SliceStable(names, func(i, j int) bool { return !isSystem(names[i]) && isSystem(names[j]) }) + if names == nil { + names = []string{} + } + return names, nil +} + +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + ks := lit(schema) + out := []model.DbObject{} + add := func(kind string, names []string) { + sort.Strings(names) + for _, n := range names { + out = append(out, model.DbObject{Name: n, Kind: kind}) + } + } + namesOf := func(f *fetched, column string) []string { + var names []string + for _, r := range f.rows { + if n, ok := f.text(r, column); ok { + names = append(names, n) + } + } + return names + } + if isVirtual(schema) { + f, err := s.fetch(opCtx, "SELECT table_name FROM system_virtual_schema.tables WHERE keyspace_name = "+ks) + if err != nil { + return nil, err + } + add("table", namesOf(f, "table_name")) + return out, nil + } + for _, q := range []struct{ kind, table, column string }{ + {"table", "tables", "table_name"}, + {"matview", "views", "view_name"}, + {"type", "types", "type_name"}, + } { + f, err := s.fetch(opCtx, "SELECT "+q.column+" FROM system_schema."+q.table+" WHERE keyspace_name = "+ks) + if err != nil { + return nil, err + } + add(q.kind, namesOf(f, q.column)) + } + for _, q := range []struct{ kind, table, column string }{ + {"function", "functions", "function_name"}, + {"aggregate", "aggregates", "aggregate_name"}, + } { + f, err := s.fetch(opCtx, "SELECT "+q.column+", argument_types FROM system_schema."+q.table+ + " WHERE keyspace_name = "+ks) + if err != nil { + return nil, err + } + var names []string + for _, r := range f.rows { + if n, ok := f.text(r, q.column); ok { + names = append(names, n+"("+strings.Join(f.textList(r, "argument_types"), ", ")+")") + } + } + add(q.kind, names) + } + f, err := s.fetch(opCtx, "SELECT index_name FROM system_schema.indexes WHERE keyspace_name = "+ks) + if err != nil { + return nil, err + } + add("index", namesOf(f, "index_name")) + return out, nil +} + +func (s *Session) ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + return s.listColumns(opCtx, schema, table) +} + +func (s *Session) listColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + catalog := "system_schema" + if isVirtual(schema) { + catalog = "system_virtual_schema" + } + f, err := s.fetch(ctx, "SELECT column_name, type, kind, position FROM "+catalog+ + ".columns WHERE keyspace_name = "+lit(schema)+" AND table_name = "+lit(table)) + if err != nil { + return nil, err + } + type ranked struct { + order int + position int32 + col model.DbColumn + } + var cols []ranked + for _, r := range f.rows { + name, ok := f.text(r, "column_name") + if !ok { + continue + } + kind, _ := f.text(r, "kind") + order, role := 3, "regular" + switch asciiLower(kind) { + case "partition_key": + order, role = 0, "partition" + case "clustering": + order, role = 1, "clustering" + case "static": + order, role = 2, "static" + } + key := order < 2 + position := int32(0) + if key { + position = f.integer(r, "position") + } + typ, _ := f.text(r, "type") + cols = append(cols, ranked{order, position, model.DbColumn{ + Name: name, + TypeName: typ, + Nullable: !key, + PrimaryKey: key, + KeyRole: model.Str(role), + }}) + } + sort.Slice(cols, func(i, j int) bool { + a, b := cols[i], cols[j] + if a.order != b.order { + return a.order < b.order + } + if a.position != b.position { + return a.position < b.position + } + return a.col.Name < b.col.Name + }) + out := make([]model.DbColumn, len(cols)) + for i, c := range cols { + out[i] = c.col + } + return out, nil +} + +// Stream runs a query and sends its rows to sink in batches, one page at a +// time. +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return 0, err + } + defer release() + iter := s.query(sql).PageSize(drivers.StreamBatch).IterContext(opCtx) + cols := iter.Columns() + if len(cols) == 0 { + if err := iter.Close(); err != nil { + return 0, fail(opCtx, err, sql) + } + return 0, apperr.Invalidf("The statement returns no rows.") + } + r := newRowReader(cols) + info := make([]model.ColumnInfo, len(cols)) + for i, c := range cols { + info[i] = model.ColumnInfo{Name: c.Name, TypeName: typeName(r.types[i]), Kind: columnKind(r.types[i])} + } + stop := func(err error) (uint64, error) { + _ = iter.Close() + return 0, err + } + if !send(opCtx, sink, drivers.StreamEvent{Columns: info}) { + return stop(apperr.CancelledErr()) + } + limit := drivers.BinaryLimit(drivers.WithFullValues(opCtx), binaryPreviewBytes) + var total uint64 + batch := make([]model.Row, 0, drivers.StreamBatch) + for iter.Scan(r.dest...) { + values := r.values(false) + row := make(model.Row, len(values)) + for i, v := range values { + cell, err := cellText(r.types[i], v, limit) + if err != nil { + _, err = stop(err) + return total, err + } + row[i] = cell + } + batch = append(batch, row) + total++ + if len(batch) == drivers.StreamBatch { + if !send(opCtx, sink, drivers.StreamEvent{Rows: batch}) { + _, err := stop(apperr.CancelledErr()) + return total, err + } + batch = make([]model.Row, 0, drivers.StreamBatch) + } + } + if err := iter.Close(); err != nil { + return total, fail(opCtx, err, sql) + } + if len(batch) > 0 && !send(opCtx, sink, drivers.StreamEvent{Rows: batch}) { + return total, apperr.CancelledErr() + } + return total, nil +} + +func send(ctx context.Context, sink chan<- drivers.StreamEvent, ev drivers.StreamEvent) bool { + select { + case sink <- ev: + return true + case <-ctx.Done(): + return false + } +} diff --git a/internal/drivers/cassandra/cassandra_test.go b/internal/drivers/cassandra/cassandra_test.go new file mode 100644 index 0000000..2868f7f --- /dev/null +++ b/internal/drivers/cassandra/cassandra_test.go @@ -0,0 +1,532 @@ +package cassandra + +import ( + "context" + "encoding/binary" + "errors" + "math" + "math/bits" + "reflect" + "strings" + "testing" + + gocql "github.com/apache/cassandra-gocql-driver/v2" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// Unit tests: no server needed. + +func native(kind gocql.Type) *ctype { return &ctype{kind: kind} } + +func be32(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) } +func be64(v uint64) []byte { return binary.BigEndian.AppendUint64(nil, v) } + +// seq encodes a tuple or UDT body; collection prefixes it with the count. +func seq(items ...[]byte) []byte { + var out []byte + for _, it := range items { + out = appendBytes(out, it) + } + return out +} + +func collection(n int, items ...[]byte) []byte { + return append(be32(uint32(n)), seq(items...)...) +} + +func text(s string) []byte { return []byte(s) } + +func litOf(t *testing.T, typ *ctype, data []byte) string { + t.Helper() + s, err := literal(typ, data) + if err != nil { + t.Fatal(err) + } + return s +} + +func cell(t *testing.T, typ *ctype, data []byte) string { + t.Helper() + s, err := cellText(typ, data, math.MaxInt) + if err != nil { + t.Fatal(err) + } + if s == nil { + return "" + } + return *s +} + +func eq[T comparable](t *testing.T, got, want T) { + t.Helper() + if got != want { + t.Errorf("got %v, want %v", got, want) + } +} + +func TestIntegersKeepEveryDigit(t *testing.T) { + eq(t, integerText(nil), "0") + eq(t, integerText([]byte{0}), "0") + eq(t, integerText([]byte{0x7f}), "127") + eq(t, integerText([]byte{0xff}), "-1") + eq(t, integerText([]byte{0x80}), "-128") + eq(t, integerText([]byte{0x00, 0xff}), "255") + // 2^64 and -(2^64) - 1 + eq(t, integerText([]byte{0x01, 0, 0, 0, 0, 0, 0, 0, 0}), "18446744073709551616") + eq(t, integerText([]byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}), "-18446744073709551617") + n := []byte{0x01, 0x8e, 0xe9, 0x0f, 0xf6, 0xc3, 0x73, 0xe0, 0xee, 0x4e, 0x3f, 0x0a, 0xd2} + eq(t, litOf(t, native(gocql.TypeVarint), n), "123456789012345678901234567890") +} + +func TestDecimalsAreExact(t *testing.T) { + eq(t, decimalText("12345", 2), "123.45") + eq(t, decimalText("-5", 3), "-0.005") + eq(t, decimalText("0", 2), "0.00") + eq(t, decimalText("7", 0), "7") + eq(t, decimalText("1", -3), "1E+3") + eq(t, decimalText("-12", -3), "-1.2E+4") + eq(t, decimalText("1", 10), "1E-10") + eq(t, litOf(t, native(gocql.TypeDecimal), append(be32(2), 0x30, 0x39)), "123.45") +} + +func TestFloatsRoundTrip(t *testing.T) { + double := func(v float64) string { return litOf(t, native(gocql.TypeDouble), be64(math.Float64bits(v))) } + float := func(v float32) string { return litOf(t, native(gocql.TypeFloat), be32(math.Float32bits(v))) } + eq(t, double(0.1), "0.1") + eq(t, float(0.1), "0.1") + eq(t, double(1.0), "1") + eq(t, double(math.NaN()), "NaN") + eq(t, double(math.Inf(1)), "Infinity") + eq(t, double(math.Inf(-1)), "-Infinity") + eq(t, double(1.5e300), "1.5e300") + eq(t, double(1e-7), "1e-7") + eq(t, double(0.0), "0") + eq(t, float(1e20), "1e20") +} + +func TestTemporalValues(t *testing.T) { + eq(t, cell(t, native(gocql.TypeTimestamp), be64(0)), "1970-01-01 00:00:00.000+0000") + eq(t, timestampText(1_714_979_289_123), "2024-05-06 07:08:09.123+0000") + eq(t, timestampText(-1), "1969-12-31 23:59:59.999+0000") + eq(t, dateText(0), "1970-01-01") + eq(t, dateText(19_849), "2024-05-06") + eq(t, dateText(-719_529), "-0001-12-31") + eq(t, cell(t, native(gocql.TypeDate), be32(1<<31)), "1970-01-01") + eq(t, cell(t, native(gocql.TypeTime), be64(25_689_123_456_789)), "07:08:09.123456789") + eq(t, litOf(t, native(gocql.TypeTimestamp), be64(0)), "'1970-01-01 00:00:00.000+0000'") +} + +// vint encodes a signed variable-length integer, as the server does. +func vint(v int64) []byte { + u := uint64(v<<1) ^ uint64(v>>63) + n := max((639-bits.LeadingZeros64(u)*9)>>6, 1) + buf := make([]byte, n) + for i, x := n-1, u; i >= 0; i, x = i-1, x>>8 { + buf[i] = byte(x) + } + if n == 9 { + buf[0] = 0xff + } else { + buf[0] |= ^byte(0xff >> (n - 1)) + } + return buf +} + +func TestDurationsReadBack(t *testing.T) { + eq(t, durationText(0, 0, 0), "0s") + eq(t, durationText(14, 3, 14_706_007_008_009), "1y2mo3d4h5m6s7ms8us9ns") + eq(t, durationText(-1, -2, -3_000_000_000), "-1mo2d3s") + dur := native(gocql.TypeDuration) + eq(t, litOf(t, dur, append(append(vint(1), vint(0)...), vint(0)...)), "1mo") + eq(t, litOf(t, dur, append(append(vint(14), vint(3)...), vint(14_706_007_008_009)...)), "1y2mo3d4h5m6s7ms8us9ns") + eq(t, litOf(t, dur, append(append(vint(-1), vint(-2)...), vint(-3_000_000_000)...)), "-1mo2d3s") +} + +func TestScalars(t *testing.T) { + eq(t, cell(t, native(gocql.TypeText), nil), "") + eq(t, cell(t, native(gocql.TypeText), text("it's")), "it's") + eq(t, litOf(t, native(gocql.TypeText), text("it's")), "'it''s'") + eq(t, cell(t, native(gocql.TypeBoolean), []byte{1}), "true") + eq(t, cell(t, native(gocql.TypeCounter), be64(uint64(math.MaxUint64-3))), "-4") + eq(t, cell(t, native(gocql.TypeBlob), []byte{0, 255}), "0x00ff") + eq(t, cell(t, native(gocql.TypeBlob), []byte{}), "0x") + eq(t, cell(t, native(gocql.TypeInet), []byte{127, 0, 0, 1}), "127.0.0.1") + ip6 := make([]byte, 16) + ip6[15] = 1 + eq(t, litOf(t, native(gocql.TypeInet), ip6), "'::1'") + id := []byte{0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, 0x14, 0x17, 0x40, 0x00} + eq(t, cell(t, native(gocql.TypeUUID), id), "123e4567-e89b-12d3-a456-426614174000") + eq(t, cell(t, native(gocql.TypeTimeUUID), id), "123e4567-e89b-12d3-a456-426614174000") + eq(t, cell(t, native(gocql.TypeTinyInt), []byte{0x80}), "-128") + eq(t, cell(t, native(gocql.TypeSmallInt), []byte{0x80, 0}), "-32768") + eq(t, cell(t, native(gocql.TypeBigInt), be64(math.MaxInt64)), "9223372036854775807") + // An empty value of a type without one shows as empty text. + eq(t, cell(t, native(gocql.TypeInt), []byte{}), "") + eq(t, litOf(t, native(gocql.TypeInt), []byte{}), "null") + if _, err := literal(native(gocql.TypeInt), []byte{1, 2}); err == nil { + t.Error("a short int should not decode") + } +} + +func TestCompositesAreCQLLiterals(t *testing.T) { + intT, textT := native(gocql.TypeInt), native(gocql.TypeText) + list := &ctype{kind: gocql.TypeList, elems: []*ctype{intT}} + eq(t, cell(t, list, collection(2, be32(1), be32(2))), "[1, 2]") + set := &ctype{kind: gocql.TypeSet, elems: []*ctype{textT}} + eq(t, cell(t, set, collection(2, text("a"), text("b'"))), "{'a', 'b'''}") + m := &ctype{kind: gocql.TypeMap, elems: []*ctype{textT, intT}} + eq(t, cell(t, m, collection(1, text("a"), be32(1))), "{'a': 1}") + tuple := &ctype{kind: gocql.TypeTuple, elems: []*ctype{intT, textT, intT}} + eq(t, cell(t, tuple, seq(be32(1), text("x"), nil)), "(1, 'x', null)") + udt := &ctype{ + kind: gocql.TypeUDT, + name: "address", + fields: []string{"street", "Zip", "floor"}, + elems: []*ctype{textT, intT, intT}, + } + eq(t, cell(t, udt, seq(text("Main"), be32(12345), nil)), `{street: 'Main', "Zip": 12345, floor: null}`) + // Fields added to the type after the value was written are null. + eq(t, cell(t, udt, seq(text("Main"))), `{street: 'Main', "Zip": null, floor: null}`) + floatT := native(gocql.TypeFloat) + vector := &ctype{kind: kindVector, elems: []*ctype{floatT}, dims: 2} + eq(t, cell(t, vector, append(be32(math.Float32bits(0.5)), be32(math.Float32bits(1.5))...)), "[0.5, 1.5]") + textVector := &ctype{kind: kindVector, elems: []*ctype{textT}, dims: 2} + eq(t, cell(t, textVector, []byte{1, 'a', 2, 'b', 'c'}), "['a', 'bc']") + nested := &ctype{kind: gocql.TypeMap, elems: []*ctype{textT, {kind: gocql.TypeList, elems: []*ctype{native(gocql.TypeBlob)}}}} + eq(t, litOf(t, nested, collection(1, text("k"), collection(1, []byte{1}))), "{'k': [0x01]}") + if _, err := literal(list, collection(3, be32(1))); err == nil { + t.Error("a short list should not decode") + } +} + +func TestBlobPreviewIsCut(t *testing.T) { + bytes := []byte(strings.Repeat("\xab", 10)) + eq(t, blob(bytes, 4), "0xabababab… (10 bytes)") + eq(t, len(blob(bytes, math.MaxInt)), 22) +} + +func TestLiteralsFollowTheColumnType(t *testing.T) { + l := func(typ, v string) string { return cqlLiteral(typ, &v) } + eq(t, l("int", "42"), "42") + eq(t, l("varint", "-12345678901234567890"), "-12345678901234567890") + eq(t, l("double", "NaN"), "NaN") + eq(t, l("double", "1.5e-3"), "1.5e-3") + eq(t, l("decimal", "1.50"), "1.50") + eq(t, l("boolean", "TRUE"), "true") + eq(t, l("text", "it's"), "'it''s'") + eq(t, l("ascii", "x"), "'x'") + eq(t, l("timestamp", "2024-05-06 07:08:09.123+0000"), "'2024-05-06 07:08:09.123+0000'") + eq(t, l("date", "2024-05-06"), "'2024-05-06'") + eq(t, l("time", "07:08:09"), "'07:08:09'") + eq(t, l("inet", "::1"), "'::1'") + eq(t, l("uuid", "123e4567-e89b-12d3-a456-426614174000"), "123e4567-e89b-12d3-a456-426614174000") + eq(t, l("blob", "0x00ff"), "0x00ff") + eq(t, l("duration", "1mo2d"), "1mo2d") + eq(t, cqlLiteral("int", nil), "null") + // Not a value of the type: quoted, so the server explains the error. + eq(t, l("int", "abc"), "'abc'") + eq(t, l("int", "1.2.3"), "'1.2.3'") + eq(t, l("blob", "xyz"), "'xyz'") + eq(t, l("boolean", "yes"), "'yes'") + // Collections, tuples, UDTs and vectors are literals already. + eq(t, l("list", "[1, 2]"), "[1, 2]") + eq(t, l("frozen>", "{'a': 1}"), "{'a': 1}") + eq(t, l("frozen
", "{zip: 1}"), "{zip: 1}") + eq(t, l("tuple", "(1, 'x')"), "(1, 'x')") + eq(t, l("vector", "[0.5, 1.5]"), "[0.5, 1.5]") + eq(t, l("FROZEN>", "['a']"), "['a']") +} + +func TestNamesAreQuotedWhenNeeded(t *testing.T) { + eq(t, quoteName("users"), "users") + eq(t, quoteName("user_id2"), "user_id2") + eq(t, quoteName("Users"), `"Users"`) + eq(t, quoteName("2fast"), `"2fast"`) + eq(t, quoteName("select"), `"select"`) + eq(t, quoteName(`a"b`), `"a""b"`) + eq(t, quoteName("with space"), `"with space"`) + eq(t, quoteName(""), `""`) +} + +func TestTypeNames(t *testing.T) { + eq(t, typeName(native(gocql.TypeInt)), "int") + eq(t, typeName(native(gocql.TypeVarchar)), "text") + list := &ctype{kind: gocql.TypeList, elems: []*ctype{native(gocql.TypeText)}} + eq(t, typeName(list), "list") + m := &ctype{kind: gocql.TypeMap, elems: []*ctype{native(gocql.TypeText), native(gocql.TypeInt)}} + eq(t, typeName(m), "map") + eq(t, columnKind(m), model.KindOther) + eq(t, typeName(&ctype{kind: kindVector, elems: []*ctype{native(gocql.TypeFloat)}, dims: 3}), "vector") + eq(t, typeName(&ctype{kind: gocql.TypeTuple, elems: []*ctype{native(gocql.TypeInt), native(gocql.TypeText)}}), + "tuple") + eq(t, typeName(&ctype{kind: gocql.TypeUDT, name: "Addr"}), `"Addr"`) + eq(t, typeName(&ctype{kind: kindUnknown}), "custom") + eq(t, columnKind(native(gocql.TypeVarint)), model.KindNumber) + eq(t, columnKind(native(gocql.TypeBlob)), model.KindBinary) + eq(t, columnKind(native(gocql.TypeUUID)), model.KindText) + eq(t, columnKind(native(gocql.TypeTimestamp)), model.KindTemporal) + eq(t, columnKind(native(gocql.TypeDuration)), model.KindTemporal) + eq(t, columnKind(native(gocql.TypeBoolean)), model.KindBool) +} + +func TestDriverTypesConvert(t *testing.T) { + intInfo := gocql.NewNativeType(4, gocql.TypeInt, "") + textInfo := gocql.NewNativeType(4, gocql.TypeVarchar, "") + eq(t, typeName(typeOf(intInfo)), "int") + tuple := gocql.TupleTypeInfo{Elems: []gocql.TypeInfo{intInfo, textInfo}} + eq(t, typeName(typeOf(tuple)), "tuple") + udt := gocql.UDTTypeInfo{Keyspace: "ks", Name: "addr", Elements: []gocql.UDTField{ + {Name: "street", Type: textInfo}, {Name: "zip", Type: intInfo}, + }} + eq(t, typeName(typeOf(udt)), "addr") + eq(t, typeName(typeOf(gocql.VectorType{SubType: intInfo, Dimensions: 2})), "vector") + m := gocql.NewNativeType(4, gocql.TypeCustom, "map>>") + eq(t, typeName(typeOf(m)), "map>") + + // A tuple column arrives as one destination per item and is joined + // back; all items null is a null tuple. + r := newRowReader([]gocql.ColumnInfo{ + {Name: "id", TypeInfo: intInfo}, + {Name: "tp", TypeInfo: tuple}, + {Name: "ad", TypeInfo: udt}, + }) + if len(r.dest) != 4 { + t.Fatalf("destinations: %d", len(r.dest)) + } + fill := func(values ...[]byte) { + for i, v := range values { + if err := r.dest[i].(gocql.Unmarshaler).UnmarshalCQL(nil, v); err != nil { + t.Fatal(err) + } + } + } + show := func() []string { + var out []string + for i, v := range r.values(true) { + out = append(out, cell(t, r.types[i], v)) + } + return out + } + fill(be32(1), be32(7), text("x"), seq(text("Main"), be32(1))) + if got := show(); !reflect.DeepEqual(got, []string{"1", "(7, 'x')", "{street: 'Main', zip: 1}"}) { + t.Errorf("got %q", got) + } + fill(be32(2), nil, text("y"), nil) + if got := show(); !reflect.DeepEqual(got, []string{"2", "(null, 'y')", ""}) { + t.Errorf("got %q", got) + } + fill(be32(3), nil, nil, nil) + if got := show(); !reflect.DeepEqual(got, []string{"3", "", ""}) { + t.Errorf("got %q", got) + } +} + +func TestContactPoints(t *testing.T) { + eq(t, contactPoint("db1", 9042), "db1:9042") + eq(t, contactPoint("db1:9043", 9042), "db1:9043") + eq(t, contactPoint("::1", 9042), "[::1]:9042") + eq(t, contactPoint("[::1]", 9042), "[::1]:9042") + eq(t, contactPoint("[::1]:9043", 9042), "[::1]:9043") +} + +func TestSyntaxErrorPositions(t *testing.T) { + sql := "SELECT *\nFROM WHERE" + // "SELECT *" is 8 chars plus the newline, then column 6. + p, ok := errorPosition(sql, "line 2:6 no viable alternative at input 'WHERE'") + eq(t, ok, true) + eq(t, p, 15) + p, ok = errorPosition("x", "line 1:0 mismatched input") + eq(t, ok, true) + eq(t, p, 0) + _, ok = errorPosition("x", "Unknown table") + eq(t, ok, false) + _, ok = errorPosition("x", "line 0:3 x") + eq(t, ok, false) + // The comment in front of every statement is taken back out. + eq(t, unprefixed("line 1:4 no viable alternative at input 'SELEC'"), "line 1:0 no viable alternative at input 'SELEC'") + eq(t, unprefixed("line 2:4 x"), "line 2:4 x") + e := dbError(gocql.ErrCodeSyntax, "line 1:11 mismatched input 'FORM'", "SELECT * FORM t") + eq(t, e.Code, "SyntaxError") + eq(t, e.Message, "line 1:7 mismatched input 'FORM'") + eq(t, *e.Position, 7) + eq(t, dbError(gocql.ErrCodeCredentials, "bad", "").Kind, "connection") + eq(t, dbError(gocql.ErrCodeInvalid, "unknown table", "").Code, "Invalid") + eq(t, dbError(0x1700, "x", "").Code, "Other") +} + +func TestUseTargets(t *testing.T) { + cases := map[string]string{ + "USE ks": "ks", + "use MyKs;": "myks", + `USE "MyKs"`: "MyKs", + ` USE "a""b" ; -- done`: `a"b`, + "/* x */ USE ks /* y */ ;": "ks", + } + for sql, want := range cases { + got, ok := useTarget(sql) + if !ok || got != want { + t.Errorf("%q: got %q %v, want %q", sql, got, ok, want) + } + } + for _, sql := range []string{"USE", "USE ks extra", `USE "open`, "USER x"} { + if got, ok := useTarget(sql); ok { + t.Errorf("%q: got %q", sql, got) + } + } +} + +func TestAliasesAreFoundOutsideStrings(t *testing.T) { + eq(t, hasAlias("SELECT id AS key FROM t"), true) + eq(t, hasAlias("select id as key from t"), true) + eq(t, hasAlias("SELECT id FROM t WHERE name = 'a as b'"), false) + eq(t, hasAlias("SELECT \"as\", assigned FROM t -- as x\n"), false) + eq(t, hasAlias("SELECT id FROM base"), false) + eq(t, hasAlias("SELECT $$ as $$ FROM t /* as */"), false) +} + +func TestPrimaryKeysAndOptions(t *testing.T) { + col := func(name, kind string, position int32, descending bool) catalogColumn { + return catalogColumn{name: name, typeName: "int", kind: kind, position: position, descending: descending} + } + columns := []catalogColumn{ + col("a", "partition_key", 0, false), + col("b", "partition_key", 1, false), + col("c", "clustering", 0, true), + col("d", "regular", -1, false), + } + eq(t, primaryKey(columns), "(a, b), c") + eq(t, primaryKey(columns[1:]), "b, c") + var out strings.Builder + writeCreate(&out, "CREATE TABLE ks.t", columns, []string{"comment = ''", "gc_grace_seconds = 864000"}) + eq(t, out.String(), "CREATE TABLE ks.t (\n a int,\n b int,\n c int,\n d int,\n "+ + "PRIMARY KEY ((a, b), c)\n)\n WITH CLUSTERING ORDER BY (c DESC)\n "+ + "AND comment = ''\n AND gc_grace_seconds = 864000;\n") + eq(t, dollarBody("return a;"), "$$return a;$$") + eq(t, dollarBody("a $$ b"), "'a $$ b'") + + shuffled := []catalogColumn{columns[3], columns[2], columns[1], columns[0]} + sortCatalogColumns(shuffled) + if !reflect.DeepEqual(shuffled, columns) { + t.Errorf("sorted: %v", shuffled) + } +} + +func TestTableOptionsComeFromTheCatalogRow(t *testing.T) { + textT := native(gocql.TypeText) + f := &fetched{ + names: []string{"comment", "gc_grace_seconds", "caching", "read_repair_chance", "speculative_retry"}, + types: []*ctype{textT, native(gocql.TypeInt), {kind: gocql.TypeMap, elems: []*ctype{textT, textT}}, + native(gocql.TypeDouble), textT}, + } + row := [][]byte{text("it's"), be32(3600), collection(1, text("keys"), text("ALL")), + be64(math.Float64bits(0.1)), nil} + want := []string{"caching = {'keys': 'ALL'}", "comment = 'it''s'", "gc_grace_seconds = 3600"} + if got := tableOptions(f, row, false); !reflect.DeepEqual(got, want) { + t.Errorf("got %q", got) + } + want = append(want, "read_repair_chance = 0.1") + if got := tableOptions(f, row, true); !reflect.DeepEqual(got, want) { + t.Errorf("legacy: got %q", got) + } +} + +func editTarget() *model.EditTarget { + col := func(name, typ string) *model.EditColumn { return &model.EditColumn{Name: name, TypeName: typ} } + return &model.EditTarget{ + Schema: model.Str("My Ks"), + Table: "items", + Columns: []*model.EditColumn{col("id", "int"), col("day", "date"), col("tags", "set"), nil}, + Key: []int{0, 1}, + } +} + +func TestEditsBecomeCQL(t *testing.T) { + changes := []model.RowChange{ + {Op: model.OpUpdate, Key: []*string{model.Str("1"), model.Str("2024-05-06")}, + Values: []model.CellValue{{Column: 2, Value: model.Str("{'a', 'b'}")}}}, + {Op: model.OpUpdate, Key: []*string{model.Str("9"), model.Str("2024-05-09")}}, + {Op: model.OpDelete, Key: []*string{model.Str("2"), model.Str("2024-05-07")}}, + {Op: model.OpInsert, Values: []model.CellValue{ + {Column: 0, Value: model.Str("3")}, + {Column: 1, Value: model.Str("2024-05-08")}, + {Column: 2, Value: nil}, + }}, + } + statements, result, err := planChanges(editTarget(), changes) + if err != nil { + t.Fatal(err) + } + want := []string{ + `UPDATE "My Ks".items SET tags = {'a', 'b'} WHERE id = 1 AND day = '2024-05-06'`, + `DELETE FROM "My Ks".items WHERE id = 2 AND day = '2024-05-07'`, + `INSERT INTO "My Ks".items (id, day, tags) VALUES (3, '2024-05-08', null)`, + } + if !reflect.DeepEqual(statements, want) { + t.Errorf("got %q", statements) + } + if result.Updated != 1 || result.Deleted != 1 || result.Inserted != 1 { + t.Errorf("counts: %+v", result) + } +} + +func TestEditsRefuseKeyChangesAndExpressions(t *testing.T) { + key := []*string{model.Str("1"), model.Str("2024-05-06")} + change := func(column int) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: key, Values: []model.CellValue{{Column: column, Value: model.Str("5")}}} + } + _, _, err := planChanges(editTarget(), []model.RowChange{change(0)}) + if err == nil || !strings.Contains(err.Error(), "primary key") { + t.Errorf("key update: %v", err) + } + _, _, err = planChanges(editTarget(), []model.RowChange{change(3)}) + if err == nil || !strings.Contains(err.Error(), "not a column") { + t.Errorf("expression: %v", err) + } + short := model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("1")}} + if _, _, err := planChanges(editTarget(), []model.RowChange{short}); err == nil { + t.Error("short key accepted") + } + nullKey := model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("1"), nil}} + if _, _, err := planChanges(editTarget(), []model.RowChange{nullKey}); err == nil { + t.Error("null key accepted") + } + empty := model.RowChange{Op: model.OpInsert} + if _, _, err := planChanges(editTarget(), []model.RowChange{empty}); err == nil { + t.Error("empty insert accepted") + } + if _, _, err := planChanges(editTarget(), []model.RowChange{{Op: "merge"}}); err == nil { + t.Error("unknown change accepted") + } +} + +func TestNoTransactions(t *testing.T) { + s := &Session{} + eq(t, s.TxState(), model.TxState{Autocommit: true}) + if _, err := s.SetAutocommit(t.Context(), false); err == nil { + t.Error("autocommit off accepted") + } + if st, err := s.SetAutocommit(t.Context(), true); err != nil || !st.Autocommit { + t.Errorf("autocommit on: %v %v", st, err) + } + if _, err := s.EndTransaction(t.Context(), true); err == nil { + t.Error("commit accepted") + } + if _, err := s.ObjectDDL(t.Context(), "ks", "x", "sequence"); err == nil { + t.Error("sequence DDL accepted") + } +} + +func TestConnectErrors(t *testing.T) { + e := connectError(errors.New("gocql: unable to create session: unable to discover protocol version: " + + "Provided username cassandra and/or password are incorrect")) + eq(t, e.Kind, "connection") + eq(t, e.Code, "AuthenticationError") + e = connectError(errors.New(`authentication required (using "org.apache.cassandra.auth.PasswordAuthenticator")`)) + eq(t, e.Code, "AuthenticationError") + e = connectError(errors.New("gocql: unable to create session: unable to connect to initial hosts: dial tcp: refused")) + eq(t, e.Code, "") + eq(t, connectError(gocql.ErrNoHosts).Message, "Enter at least one contact point.") + eq(t, mapError(gocql.ErrNoConnections, "").Message, noNodeMessage) + eq(t, mapError(context.Canceled, "").Kind, "cancelled") +} diff --git a/internal/drivers/cassandra/ddl.go b/internal/drivers/cassandra/ddl.go new file mode 100644 index 0000000..10e933c --- /dev/null +++ b/internal/drivers/cassandra/ddl.go @@ -0,0 +1,442 @@ +package cassandra + +import ( + "context" + "sort" + "strings" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// ObjectDDL builds the CREATE statements from system_schema: DESCRIBE is a +// cqlsh command, not part of the protocol. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + switch kind { + case "keyspace", "table", "matview", "type", "function", "aggregate", "index": + default: + return "", apperr.Invalidf("LowQuery cannot script a %s on Cassandra.", kind) + } + opCtx, release, err := s.acquire(ctx) + if err != nil { + return "", err + } + defer release() + switch kind { + case "keyspace": + return s.keyspaceDDL(opCtx, name) + case "table": + return s.tableDDL(opCtx, schema, name) + case "matview": + return s.viewDDL(opCtx, schema, name) + case "type": + return s.typeDDL(opCtx, schema, name) + case "function": + return s.functionDDL(opCtx, schema, name) + case "aggregate": + return s.aggregateDDL(opCtx, schema, name) + default: + return s.indexDDL(opCtx, schema, name) + } +} + +func (s *Session) keyspaceDDL(ctx context.Context, name string) (string, error) { + f, err := s.fetch(ctx, "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = "+lit(name)) + if err != nil || len(f.rows) == 0 { + return "", err + } + row := f.rows[0] + replication, ok := f.literalOf(row, "replication") + if !ok { + replication = "{}" + } + durable, ok := f.literalOf(row, "durable_writes") + if !ok { + durable = "true" + } + return "CREATE KEYSPACE " + quoteName(name) + " WITH replication = " + replication + + "\n AND durable_writes = " + durable + ";\n", nil +} + +func (s *Session) typeDDL(ctx context.Context, keyspace, name string) (string, error) { + f, err := s.fetch(ctx, "SELECT * FROM system_schema.types WHERE keyspace_name = "+lit(keyspace)+ + " AND type_name = "+lit(name)) + if err != nil || len(f.rows) == 0 { + return "", err + } + row := f.rows[0] + names := f.textList(row, "field_names") + types := f.textList(row, "field_types") + var fields []string + for i := 0; i < len(names) && i < len(types); i++ { + fields = append(fields, " "+quoteName(names[i])+" "+types[i]) + } + return "CREATE TYPE " + quoteName(keyspace) + "." + quoteName(name) + " (\n" + + strings.Join(fields, ",\n") + "\n);\n", nil +} + +func (s *Session) tableDDL(ctx context.Context, keyspace, name string) (string, error) { + f, err := s.fetch(ctx, "SELECT * FROM system_schema.tables WHERE keyspace_name = "+lit(keyspace)+ + " AND table_name = "+lit(name)) + if err != nil || len(f.rows) == 0 { + return "", err + } + columns, err := s.catalogColumns(ctx, keyspace, name) + if err != nil { + return "", err + } + var out strings.Builder + writeCreate(&out, "CREATE TABLE "+quoteName(keyspace)+"."+quoteName(name), columns, + tableOptions(f, f.rows[0], s.legacy())) + out.WriteByte('\n') + indexes, err := s.indexStatements(ctx, keyspace, &name, nil) + if err != nil { + return "", err + } + for _, statement := range indexes { + out.WriteString(statement) + out.WriteByte('\n') + } + return out.String(), nil +} + +func (s *Session) viewDDL(ctx context.Context, keyspace, name string) (string, error) { + f, err := s.fetch(ctx, "SELECT * FROM system_schema.views WHERE keyspace_name = "+lit(keyspace)+ + " AND view_name = "+lit(name)) + if err != nil || len(f.rows) == 0 { + return "", err + } + row := f.rows[0] + columns, err := s.catalogColumns(ctx, keyspace, name) + if err != nil { + return "", err + } + base, _ := f.text(row, "base_table_name") + selected := "*" + if !f.boolean(row, "include_all_columns") { + names := make([]string, len(columns)) + for i, c := range columns { + names[i] = quoteName(c.name) + } + selected = strings.Join(names, ", ") + } + where, _ := f.text(row, "where_clause") + header := "CREATE MATERIALIZED VIEW " + quoteName(keyspace) + "." + quoteName(name) + " AS\n SELECT " + + selected + "\n FROM " + quoteName(keyspace) + "." + quoteName(base) + "\n WHERE " + where + var out strings.Builder + writePrimaryKey(&out, header, columns, tableOptions(f, row, s.legacy())) + return out.String(), nil +} + +type catalogColumn struct { + name string + typeName string + // partition_key, clustering, static or regular. + kind string + position int32 + descending bool +} + +func (c catalogColumn) rank() int { + switch c.kind { + case "partition_key": + return 0 + case "clustering": + return 1 + case "static": + return 2 + } + return 3 +} + +func (s *Session) catalogColumns(ctx context.Context, keyspace, table string) ([]catalogColumn, error) { + f, err := s.fetch(ctx, "SELECT column_name, type, kind, position, clustering_order "+ + "FROM system_schema.columns WHERE keyspace_name = "+lit(keyspace)+" AND table_name = "+lit(table)) + if err != nil { + return nil, err + } + var cols []catalogColumn + for _, r := range f.rows { + name, ok := f.text(r, "column_name") + if !ok { + continue + } + typ, ok := f.text(r, "type") + if !ok { + continue + } + kind, _ := f.text(r, "kind") + order, _ := f.text(r, "clustering_order") + cols = append(cols, catalogColumn{ + name: name, + typeName: typ, + kind: asciiLower(kind), + position: f.integer(r, "position"), + descending: strings.EqualFold(order, "desc"), + }) + } + sortCatalogColumns(cols) + return cols, nil +} + +func sortCatalogColumns(cols []catalogColumn) { + sort.Slice(cols, func(i, j int) bool { + a, b := cols[i], cols[j] + if a.rank() != b.rank() { + return a.rank() < b.rank() + } + if a.position != b.position { + return a.position < b.position + } + return a.name < b.name + }) +} + +// indexStatements returns the CREATE INDEX statements of a table, or of the +// one index named only. +func (s *Session) indexStatements(ctx context.Context, keyspace string, table, only *string) ([]string, error) { + f, err := s.fetch(ctx, "SELECT * FROM system_schema.indexes WHERE keyspace_name = "+lit(keyspace)) + if err != nil { + return nil, err + } + var out []string + for _, row := range f.rows { + index, ok1 := f.text(row, "index_name") + on, ok2 := f.text(row, "table_name") + if !ok1 || !ok2 { + continue + } + if (table != nil && *table != on) || (only != nil && *only != index) { + continue + } + kind, _ := f.text(row, "kind") + var options [][2]string + target, class, hasClass := "", "", false + for _, kv := range f.textMap(row, "options") { + switch kv[0] { + case "target": + if target == "" { + target = kv[1] + continue + } + case "class_name": + if !hasClass { + class, hasClass = kv[1], true + continue + } + } + options = append(options, kv) + } + custom := "" + if kind == "CUSTOM" { + custom = "CUSTOM " + } + statement := "CREATE " + custom + "INDEX " + quoteName(index) + " ON " + quoteName(keyspace) + "." + + quoteName(on) + " (" + target + ")" + if hasClass { + statement += " USING " + quoteStr(class) + if len(options) > 0 { + sort.Slice(options, func(i, j int) bool { + if options[i][0] != options[j][0] { + return options[i][0] < options[j][0] + } + return options[i][1] < options[j][1] + }) + pairs := make([]string, len(options)) + for i, kv := range options { + pairs[i] = quoteStr(kv[0]) + ": " + quoteStr(kv[1]) + } + statement += " WITH OPTIONS = {" + strings.Join(pairs, ", ") + "}" + } + } + out = append(out, statement+";") + } + return out, nil +} + +func (s *Session) indexDDL(ctx context.Context, keyspace, name string) (string, error) { + statements, err := s.indexStatements(ctx, keyspace, nil, &name) + if err != nil { + return "", err + } + return strings.Join(statements, "\n"), nil +} + +// routineRow finds a function or aggregate, named name(argument types) in +// the tree. +func (s *Session) routineRow(ctx context.Context, table, column, keyspace, name string) (*fetched, [][]byte, error) { + bare, args, found := strings.Cut(name, "(") + if found { + args = strings.TrimRight(args, ")") + } + f, err := s.fetch(ctx, "SELECT * FROM system_schema."+table+" WHERE keyspace_name = "+lit(keyspace)+ + " AND "+column+" = "+lit(bare)) + if err != nil { + return nil, nil, err + } + for _, r := range f.rows { + if strings.Join(f.textList(r, "argument_types"), ", ") == strings.TrimSpace(args) { + return f, r, nil + } + } + return nil, nil, nil +} + +func (s *Session) functionDDL(ctx context.Context, keyspace, name string) (string, error) { + f, row, err := s.routineRow(ctx, "functions", "function_name", keyspace, name) + if err != nil || row == nil { + return "", err + } + names := f.textList(row, "argument_names") + types := f.textList(row, "argument_types") + var args []string + for i := 0; i < len(names) && i < len(types); i++ { + args = append(args, quoteName(names[i])+" "+types[i]) + } + onNull := "RETURNS NULL ON NULL INPUT" + if f.boolean(row, "called_on_null_input") { + onNull = "CALLED ON NULL INPUT" + } + body, _ := f.text(row, "body") + fn, ok := f.text(row, "function_name") + if !ok { + fn = name + } + returns, _ := f.text(row, "return_type") + language, _ := f.text(row, "language") + return "CREATE OR REPLACE FUNCTION " + quoteName(keyspace) + "." + quoteName(fn) + " (" + + strings.Join(args, ", ") + ")\n " + onNull + "\n RETURNS " + returns + "\n LANGUAGE " + + language + "\n AS " + dollarBody(body) + ";\n", nil +} + +func (s *Session) aggregateDDL(ctx context.Context, keyspace, name string) (string, error) { + f, row, err := s.routineRow(ctx, "aggregates", "aggregate_name", keyspace, name) + if err != nil || row == nil { + return "", err + } + agg, ok := f.text(row, "aggregate_name") + if !ok { + agg = name + } + stateFunc, _ := f.text(row, "state_func") + stateType, _ := f.text(row, "state_type") + out := "CREATE OR REPLACE AGGREGATE " + quoteName(keyspace) + "." + quoteName(agg) + " (" + + strings.Join(f.textList(row, "argument_types"), ", ") + ")\n SFUNC " + quoteName(stateFunc) + + "\n STYPE " + stateType + if fin, ok := f.text(row, "final_func"); ok { + out += "\n FINALFUNC " + quoteName(fin) + } + if init, ok := f.text(row, "initcond"); ok { + out += "\n INITCOND " + init + } + return out + ";\n", nil +} + +// tableOptions are the options a CREATE TABLE / CREATE MATERIALIZED VIEW +// can carry, in the order cqlsh writes them, taken from the catalog row. +func tableOptions(f *fetched, row [][]byte, legacy bool) []string { + names := []string{ + "additional_write_policy", + "allow_auto_snapshot", + "bloom_filter_fp_chance", + "caching", + "comment", + "compaction", + "compression", + "crc_check_chance", + "default_time_to_live", + "gc_grace_seconds", + "incremental_backups", + "max_index_interval", + "memtable", + "memtable_flush_period_in_ms", + "min_index_interval", + "read_repair", + "speculative_retry", + } + // Cassandra 3.x still has the read repair chances that 4.0 removed (it + // refuses them as options). + if legacy { + names = append(names, "dclocal_read_repair_chance", "read_repair_chance") + } + var out []string + for _, name := range names { + if v, ok := f.literalOf(row, name); ok { + out = append(out, name+" = "+v) + } + } + return out +} + +func writeCreate(out *strings.Builder, header string, columns []catalogColumn, options []string) { + out.WriteString(header + " (\n") + for _, c := range columns { + static := "" + if c.kind == "static" { + static = " static" + } + out.WriteString(" " + quoteName(c.name) + " " + c.typeName + static + ",\n") + } + out.WriteString(" PRIMARY KEY (" + primaryKey(columns) + ")\n)") + writeWith(out, columns, options) +} + +// writePrimaryKey writes a materialized view, whose key follows the select +// rather than a column list. +func writePrimaryKey(out *strings.Builder, header string, columns []catalogColumn, options []string) { + out.WriteString(header + "\n PRIMARY KEY (" + primaryKey(columns) + ")") + writeWith(out, columns, options) +} + +func writeWith(out *strings.Builder, columns []catalogColumn, options []string) { + var clustering []string + for _, c := range columns { + if c.kind == "clustering" { + order := "ASC" + if c.descending { + order = "DESC" + } + clustering = append(clustering, quoteName(c.name)+" "+order) + } + } + var parts []string + if len(clustering) > 0 { + parts = append(parts, "CLUSTERING ORDER BY ("+strings.Join(clustering, ", ")+")") + } + parts = append(parts, options...) + for i, part := range parts { + if i == 0 { + out.WriteString("\n WITH " + part) + } else { + out.WriteString("\n AND " + part) + } + } + out.WriteString(";\n") +} + +// primaryKey is "(a, b), c, d" for a table keyed by (a, b) with clustering +// columns c, d. +func primaryKey(columns []catalogColumn) string { + var partition, clustering []string + for _, c := range columns { + switch c.kind { + case "partition_key": + partition = append(partition, quoteName(c.name)) + case "clustering": + clustering = append(clustering, quoteName(c.name)) + } + } + head := "(" + strings.Join(partition, ", ") + ")" + if len(partition) == 1 { + head = partition[0] + } + return strings.Join(append([]string{head}, clustering...), ", ") +} + +// dollarBody writes a function body as $$...$$, or as a quoted string when +// it holds $$. +func dollarBody(body string) string { + if strings.Contains(body, "$$") { + return quoteStr(body) + } + return "$$" + body + "$$" +} diff --git a/internal/drivers/cassandra/edit.go b/internal/drivers/cassandra/edit.go new file mode 100644 index 0000000..98633c2 --- /dev/null +++ b/internal/drivers/cassandra/edit.go @@ -0,0 +1,281 @@ +package cassandra + +import ( + "context" + "strings" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +// editable says whether the rows of a result can be edited: a SELECT on one +// table whose columns include its whole primary key. An empty reason comes +// with a target. +func (s *Session) editable(ctx context.Context, sql string, isSelect bool, origins []resultColumn) (*model.EditTarget, string) { + if !isSelect { + return nil, "Only the rows of a SELECT can be edited." + } + if len(origins) == 0 { + return nil, "The result has no columns." + } + first := origins[0] + for _, c := range origins { + if c.keyspace != first.keyspace || c.table != first.table { + return nil, "The result does not come from a single table." + } + } + if isSystem(first.keyspace) { + return nil, "System tables are read-only." + } + if hasAlias(sql) { + return nil, "Columns with an alias (AS) cannot be matched to the table." + } + meta, err := s.tableMeta(ctx, first.keyspace, first.table) + if err != nil { + return nil, "The table's key could not be read." + } + if meta.view { + return nil, "Materialized views cannot be edited." + } + for _, c := range meta.columns { + if c.TypeName == "counter" { + return nil, "Counter tables cannot be edited in the grid." + } + } + key := []int{} + var missing []string + for _, c := range meta.columns { + if !c.PrimaryKey { + continue + } + found := -1 + for i, o := range origins { + if o.name == c.Name { + found = i + break + } + } + if found >= 0 { + key = append(key, found) + } else { + missing = append(missing, quoteName(c.Name)) + } + } + if len(key) == 0 && len(missing) == 0 { + return nil, "The table has no primary key." + } + if len(missing) > 0 { + return nil, "The result must include the whole primary key (missing " + strings.Join(missing, ", ") + ")." + } + columns := make([]*model.EditColumn, len(origins)) + for i, o := range origins { + for _, c := range meta.columns { + if c.Name == o.name { + columns[i] = &model.EditColumn{Name: c.Name, TypeName: c.TypeName} + break + } + } + } + keyspace := first.keyspace + return &model.EditTarget{Schema: &keyspace, Table: first.table, Columns: columns, Key: key}, "" +} + +func (s *Session) tableMeta(ctx context.Context, keyspace, table string) (*tableMeta, error) { + id := [2]string{keyspace, table} + if m := s.tables[id]; m != nil { + return m, nil + } + columns, err := s.listColumns(ctx, keyspace, table) + if err != nil { + return nil, err + } + views, err := s.fetch(ctx, "SELECT view_name FROM system_schema.views WHERE keyspace_name = "+lit(keyspace)+ + " AND view_name = "+lit(table)) + if err != nil { + return nil, err + } + meta := &tableMeta{columns: columns, view: len(views.rows) > 0} + s.tables[id] = meta + return meta, nil +} + +// ApplyChanges saves the grid's changes as one logged batch, which +// Cassandra applies completely or not at all. CQL writes are upserts, so an +// UPDATE or DELETE whose row was removed meanwhile does not fail: the +// counts are the statements sent. There is no transaction to join. +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + statements, result, err := planChanges(&req.Target, req.Changes) + if err != nil { + return nil, err + } + started := time.Now() + var sql string + switch len(statements) { + case 0: + return result, nil + case 1: + sql = statements[0] + default: + sql = "BEGIN BATCH\n" + strings.Join(statements, ";\n") + ";\nAPPLY BATCH" + } + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + if _, err := s.run(opCtx, sql, 0); err != nil { + return nil, err + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + return result, nil +} + +func planChanges(target *model.EditTarget, changes []model.RowChange) ([]string, *model.ApplyResult, error) { + table := quoteName(target.Table) + if target.Schema != nil { + table = quoteName(*target.Schema) + "." + table + } + keyColumns := make([]*model.EditColumn, len(target.Key)) + for i, k := range target.Key { + c, err := columnAt(target, k) + if err != nil { + return nil, nil, err + } + keyColumns[i] = c + } + condition := func(key []*string) (string, error) { + if len(key) != len(keyColumns) { + return "", apperr.Invalidf("The row's key is incomplete.") + } + parts := make([]string, len(key)) + for i, c := range keyColumns { + if key[i] == nil { + return "", apperr.Invalidf("The key column %s is empty.", c.Name) + } + parts[i] = quoteName(c.Name) + " = " + cqlLiteral(c.TypeName, key[i]) + } + return strings.Join(parts, " AND "), nil + } + var statements []string + result := &model.ApplyResult{} + for _, change := range changes { + switch change.Op { + case model.OpUpdate: + if len(change.Values) == 0 { + continue + } + sets := make([]string, 0, len(change.Values)) + for _, v := range change.Values { + c, err := columnAt(target, v.Column) + if err != nil { + return nil, nil, err + } + for _, k := range keyColumns { + if k.Name == c.Name { + return nil, nil, apperr.Invalidf("%s is part of the primary key, which CQL cannot update. "+ + "Delete the row and insert it again.", c.Name) + } + } + sets = append(sets, quoteName(c.Name)+" = "+cqlLiteral(c.TypeName, v.Value)) + } + where, err := condition(change.Key) + if err != nil { + return nil, nil, err + } + statements = append(statements, "UPDATE "+table+" SET "+strings.Join(sets, ", ")+" WHERE "+where) + result.Updated++ + case model.OpDelete: + where, err := condition(change.Key) + if err != nil { + return nil, nil, err + } + statements = append(statements, "DELETE FROM "+table+" WHERE "+where) + result.Deleted++ + case model.OpInsert: + if len(change.Values) == 0 { + return nil, nil, apperr.Invalidf("Enter a value for the new row.") + } + names := make([]string, len(change.Values)) + literals := make([]string, len(change.Values)) + for i, v := range change.Values { + c, err := columnAt(target, v.Column) + if err != nil { + return nil, nil, err + } + names[i] = quoteName(c.Name) + literals[i] = cqlLiteral(c.TypeName, v.Value) + } + statements = append(statements, "INSERT INTO "+table+" ("+strings.Join(names, ", ")+") VALUES ("+ + strings.Join(literals, ", ")+")") + result.Inserted++ + default: + return nil, nil, apperr.Invalidf("Unknown change %q.", change.Op) + } + } + return statements, result, nil +} + +func columnAt(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("Column %d is not a column of the table and cannot be saved.", index+1) +} + +// hasAlias is true when the text has the word AS outside strings, quoted +// names and comments. +func hasAlias(sql string) bool { + b := sql + found := false + var word strings.Builder + flush := func() { + if strings.EqualFold(word.String(), "as") { + found = true + } + word.Reset() + } + for i := 0; i < len(b); i++ { + c := b[i] + switch { + case c == '\'' || c == '"': + flush() + i++ + for i < len(b) { + if b[i] == c { + if i+1 < len(b) && b[i+1] == c { + i++ + } else { + break + } + } + i++ + } + case c == '$' && i+1 < len(b) && b[i+1] == '$': + flush() + if p := strings.Index(b[i+2:], "$$"); p >= 0 { + i = i + 2 + p + 1 + } else { + i = len(b) + } + case (c == '-' && i+1 < len(b) && b[i+1] == '-') || (c == '/' && i+1 < len(b) && b[i+1] == '/'): + flush() + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(b) && b[i+1] == '*': + flush() + if p := strings.Index(b[i+2:], "*/"); p >= 0 { + i = i + 2 + p + 1 + } else { + i = len(b) + } + case isWordByte(c): + word.WriteByte(c) + default: + flush() + } + } + flush() + return found +} diff --git a/internal/drivers/cassandra/errors.go b/internal/drivers/cassandra/errors.go new file mode 100644 index 0000000..30ec68a --- /dev/null +++ b/internal/drivers/cassandra/errors.go @@ -0,0 +1,168 @@ +package cassandra + +import ( + "context" + "errors" + "io" + "net" + "strconv" + "strings" + "unicode/utf8" + + gocql "github.com/apache/cassandra-gocql-driver/v2" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// codeNames are the server's error codes, named as the Rust driver named +// them (the interface treats AuthenticationError as an authentication +// failure). +var codeNames = map[int]string{ + gocql.ErrCodeServer: "ServerError", + gocql.ErrCodeProtocol: "ProtocolError", + gocql.ErrCodeCredentials: "AuthenticationError", + gocql.ErrCodeUnavailable: "Unavailable", + gocql.ErrCodeOverloaded: "Overloaded", + gocql.ErrCodeBootstrapping: "IsBootstrapping", + gocql.ErrCodeTruncate: "TruncateError", + gocql.ErrCodeWriteTimeout: "WriteTimeout", + gocql.ErrCodeReadTimeout: "ReadTimeout", + gocql.ErrCodeReadFailure: "ReadFailure", + gocql.ErrCodeFunctionFailure: "FunctionFailure", + gocql.ErrCodeWriteFailure: "WriteFailure", + gocql.ErrCodeSyntax: "SyntaxError", + gocql.ErrCodeUnauthorized: "Unauthorized", + gocql.ErrCodeInvalid: "Invalid", + gocql.ErrCodeConfig: "ConfigError", + gocql.ErrCodeAlreadyExists: "AlreadyExists", + gocql.ErrCodeUnprepared: "Unprepared", +} + +const noNodeMessage = "No node accepts requests. If a local datacenter is set, check its name: only its nodes are used." + +// isAuthText says whether a connection error is an authentication failure. +// gocql keeps only the text of the server's error when it fails to connect +// ("Provided username x and/or password are incorrect"). +func isAuthText(text string) bool { + t := strings.ToLower(text) + return strings.Contains(t, "authenticat") || strings.Contains(t, "credentials") || + strings.Contains(t, "and/or password") +} + +func connectError(err error) *apperr.Error { + text := err.Error() + if errors.Is(err, gocql.ErrNoHosts) { + text = "Enter at least one contact point." + } + e := apperr.New(apperr.Connection, text) + var re gocql.RequestError + if isAuthText(text) || (errors.As(err, &re) && re.Code() == gocql.ErrCodeCredentials) { + e.Code = "AuthenticationError" + } + return e +} + +// mapError turns a driver error into the app's error. sql is the +// statement as the user wrote it, for the position of syntax errors. +func mapError(err error, sql string) *apperr.Error { + var e *apperr.Error + if errors.As(err, &e) { + return e + } + var re gocql.RequestError + if errors.As(err, &re) { + return dbError(re.Code(), re.Message(), sql) + } + switch { + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + return apperr.CancelledErr() + case errors.Is(err, gocql.ErrNoConnections): + return apperr.New(apperr.Connection, noNodeMessage) + case errors.Is(err, gocql.ErrSessionClosed), errors.Is(err, gocql.ErrConnectionClosed), + errors.Is(err, gocql.ErrNoStreams), errors.Is(err, gocql.ErrTooManyTimeouts), + errors.Is(err, gocql.ErrTimeoutNoResponse), errors.Is(err, io.EOF), + errors.Is(err, io.ErrUnexpectedEOF), errors.Is(err, net.ErrClosed): + return apperr.New(apperr.Connection, err.Error()) + } + var ne net.Error + if errors.As(err, &ne) { + return apperr.New(apperr.Connection, err.Error()) + } + return apperr.New(apperr.Database, err.Error()) +} + +func dbError(code int, message, sql string) *apperr.Error { + name, ok := codeNames[code] + if !ok { + name = "Other" + } + kind := apperr.Database + if code == gocql.ErrCodeCredentials { + kind = apperr.Connection + } + if code == gocql.ErrCodeSyntax { + message = unprefixed(message) + } + e := apperr.New(kind, message) + e.Code = name + if code == gocql.ErrCodeSyntax && sql != "" { + if p, ok := errorPosition(sql, message); ok { + e.Position = &p + } + } + return e +} + +// unprefixed moves the column of "line 1:N" back over the comment every +// statement is sent behind (see unprepared). +func unprefixed(message string) string { + i := strings.Index(message, "line 1:") + if i < 0 { + return message + } + start := i + len("line 1:") + end := start + for end < len(message) && message[end] >= '0' && message[end] <= '9' { + end++ + } + col, err := strconv.Atoi(message[start:end]) + if err != nil { + return message + } + col = max(col-len(unprepared), 0) + return message[:start] + strconv.Itoa(col) + message[end:] +} + +// errorPosition reads "line 1:7 no viable alternative at input ..." as a +// 0-based character offset into sql. +func errorPosition(sql, message string) (int, bool) { + i := strings.Index(message, "line ") + if i < 0 { + return 0, false + } + rest := message[i+len("line "):] + lineText, rest, ok := strings.Cut(rest, ":") + if !ok { + return 0, false + } + line, err := strconv.Atoi(strings.TrimSpace(lineText)) + if err != nil || line < 1 { + return 0, false + } + end := 0 + for end < len(rest) && rest[end] >= '0' && rest[end] <= '9' { + end++ + } + col, err := strconv.Atoi(rest[:end]) + if err != nil { + return 0, false + } + before := 0 + for n, l := range strings.Split(sql, "\n") { + if n >= line-1 { + break + } + before += utf8.RuneCountInString(l) + 1 + } + return before + col, true +} diff --git a/internal/drivers/cassandra/integration_test.go b/internal/drivers/cassandra/integration_test.go new file mode 100644 index 0000000..d186931 --- /dev/null +++ b/internal/drivers/cassandra/integration_test.go @@ -0,0 +1,654 @@ +package cassandra + +// Tests against a real server. They only run with LQ_CASSANDRA_HOST set +// (and optionally LQ_CASSANDRA_PORT, LQ_CASSANDRA_USER, +// LQ_CASSANDRA_PASSWORD, LQ_CASSANDRA_DC). Every test works in a keyspace +// of its own, named uniquely and dropped at the end. + +import ( + "context" + "encoding/json" + "fmt" + "os" + "reflect" + "sort" + "strconv" + "strings" + "sync/atomic" + "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 cassSession(t *testing.T) *Session { + t.Helper() + host := os.Getenv("LQ_CASSANDRA_HOST") + if host == "" { + t.Skip("LQ_CASSANDRA_HOST is not set") + } + profile := model.DefaultProfile() + profile.Name = "test" + profile.Engine = model.Cassandra + profile.Host = host + profile.Port = 9042 + if p, err := strconv.ParseUint(os.Getenv("LQ_CASSANDRA_PORT"), 10, 16); err == nil { + profile.Port = uint16(p) + } + profile.User = os.Getenv("LQ_CASSANDRA_USER") + profile.Datacenter = os.Getenv("LQ_CASSANDRA_DC") + profile.SslMode = model.SslDisable + var password *string + if pw := os.Getenv("LQ_CASSANDRA_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 +} + +var keyspaceSeq atomic.Int64 + +// keyspace creates a keyspace named prefix plus a unique suffix, dropped +// when the test ends. +func keyspace(t *testing.T, s *Session, prefix string) string { + t.Helper() + name := fmt.Sprintf("%s_%s%d", prefix, strconv.FormatInt(time.Now().UnixNano()%1e12, 36), keyspaceSeq.Add(1)) + run(t, s, "CREATE KEYSPACE "+name+" WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", 0) + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if _, err := s.Execute(ctx, model.ExecRequest{SQL: "DROP KEYSPACE IF EXISTS " + name}); err != nil { + t.Errorf("drop %s: %v", name, err) + } + }) + return name +} + +func run(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 execErr(t *testing.T, s *Session, sql string) *apperr.Error { + t.Helper() + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: sql, MaxRows: 10}) + if err == nil { + t.Fatalf("%s: no error", sql) + } + return apperr.From(err) +} + +// texts shows rows with NULL as "", 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] = "" + } else { + out[i][j] = *v + } + } + } + return out +} + +func firstRow(t *testing.T, r *model.ExecResult) []string { + t.Helper() + if len(r.Rows) == 0 { + t.Fatal("no rows") + } + return texts(r.Rows)[0] +} + +func TestCassandraTypesLimitsAndErrors(t *testing.T) { + s := cassSession(t) + ctx := context.Background() + if !strings.HasPrefix(s.ServerVersion(), "Apache Cassandra ") { + t.Fatalf("version: %s", s.ServerVersion()) + } + if st := s.TxState(); !st.Autocommit || st.InTransaction { + t.Fatalf("tx state: %+v", st) + } + if _, err := s.SetAutocommit(ctx, false); err == nil { + t.Fatal("autocommit off accepted") + } + if _, err := s.EndTransaction(ctx, true); err == nil { + t.Fatal("commit accepted") + } + + ks := keyspace(t, s, "lq_go_types") + run(t, s, "CREATE TYPE "+ks+".addr (street text, zip int, tags set)", 0) + run(t, s, `CREATE TABLE `+ks+`.t ( + id int PRIMARY KEY, a ascii, b bigint, bl blob, bo boolean, d date, de decimal, + du double, dur duration, f float, i inet, s smallint, t text, ti time, + ts timestamp, tu timeuuid, ty tinyint, u uuid, v varint, + l list, st set, m map>>, + tp tuple, ad frozen, n int, ntp tuple)`, 0) + run(t, s, `INSERT INTO `+ks+`.t (id, a, b, bl, bo, d, de, du, dur, f, i, s, t, ti, ts, tu, ty, u, v, + l, st, m, tp, ad) VALUES ( + 1, 'ascii', 9223372036854775807, 0x00ff10, true, '2024-05-06', + 12345678901234567890.123456789, 0.1, 1y2mo3d4h5m6s7ms8us9ns, 1.5, '::1', -32768, + 'it''s é', '07:08:09.123456789', '2024-05-06 07:08:09.123+0000', + 50554d6e-29bb-11e5-b345-feff819cdc9f, -128, 123e4567-e89b-12d3-a456-426614174000, + -123456789012345678901234567890, + [1, 2, 3], {'b', 'a''x'}, {'k': [1, 2]}, (7, 'x', false), + {street: 'Main', zip: 12345, tags: {'p', 'q'}})`, 0) + r := run(t, s, "SELECT * FROM "+ks+".t", 100) + by := func(name string) int { + for i, c := range r.Columns { + if c.Name == name { + return i + } + } + t.Fatalf("no column %s", name) + return -1 + } + cells := firstRow(t, r) + want := map[string]string{ + "a": "ascii", + "b": "9223372036854775807", + "bl": "0x00ff10", + "bo": "true", + "d": "2024-05-06", + "de": "12345678901234567890.123456789", + "du": "0.1", + "dur": "1y2mo3d4h5m6s7ms8us9ns", + "f": "1.5", + "i": "::1", + "s": "-32768", + "t": "it's é", + "ti": "07:08:09.123456789", + "ts": "2024-05-06 07:08:09.123+0000", + "tu": "50554d6e-29bb-11e5-b345-feff819cdc9f", + "ty": "-128", + "u": "123e4567-e89b-12d3-a456-426614174000", + "v": "-123456789012345678901234567890", + "l": "[1, 2, 3]", + "st": "{'a''x', 'b'}", + "m": "{'k': [1, 2]}", + "tp": "(7, 'x', false)", + "ad": "{street: 'Main', zip: 12345, tags: {'p', 'q'}}", + "n": "", + "ntp": "", + } + for name, v := range want { + if got := cells[by(name)]; got != v { + t.Errorf("%s: got %q, want %q", name, got, v) + } + } + typeOfColumn := func(name string) string { return r.Columns[by(name)].TypeName } + for name, typ := range map[string]string{ + "l": "list", + // Result metadata does not say which collections and UDTs are frozen. + "m": "map>", + "tp": "tuple", + "ad": "addr", + "v": "varint", + } { + if got := typeOfColumn(name); got != typ { + t.Errorf("type of %s: got %q, want %q", name, got, typ) + } + } + for name, kind := range map[string]model.ValueKind{ + "de": model.KindNumber, "bl": model.KindBinary, "ts": model.KindTemporal, "st": model.KindOther, + } { + if got := r.Columns[by(name)].Kind; got != kind { + t.Errorf("kind of %s: got %q, want %q", name, got, kind) + } + } + + // Every composite cell is a literal the server reads back. + cell := func(name string) string { return cells[by(name)] } + run(t, s, fmt.Sprintf("INSERT INTO %s.t (id, l, st, m, tp, ad) VALUES (2, %s, %s, %s, %s, %s)", + ks, cell("l"), cell("st"), cell("m"), cell("tp"), cell("ad")), 0) + again := run(t, s, "SELECT l, st, m, tp, ad FROM "+ks+".t WHERE id = 2", 10) + if got, want := firstRow(t, again), []string{cell("l"), cell("st"), cell("m"), cell("tp"), cell("ad")}; !reflect.DeepEqual(got, want) { + t.Errorf("round trip: got %q, want %q", got, want) + } + + // Counters are not editable. + run(t, s, "CREATE TABLE "+ks+".c (id int PRIMARY KEY, n counter)", 0) + run(t, s, "UPDATE "+ks+".c SET n = n + 5 WHERE id = 1", 0) + c := run(t, s, "SELECT id, n FROM "+ks+".c", 10) + if c.Columns[1].TypeName != "counter" { + t.Errorf("counter type: %s", c.Columns[1].TypeName) + } + if got := firstRow(t, c); !reflect.DeepEqual(got, []string{"1", "5"}) { + t.Errorf("counter: %q", got) + } + if c.ReadOnlyReason == nil || !strings.Contains(*c.ReadOnlyReason, "Counter") { + t.Errorf("counter reason: %v", c.ReadOnlyReason) + } + + // The row limit is applied by paging. + run(t, s, "CREATE TABLE "+ks+".many (id int PRIMARY KEY, v int)", 0) + for i := 0; i < 120; i++ { + run(t, s, fmt.Sprintf("INSERT INTO %s.many (id, v) VALUES (%d, %d)", ks, i, i), 0) + } + for _, tc := range []struct { + limit, rows int + truncated bool + }{{10, 10, true}, {120, 120, false}, {0, 120, false}} { + r := run(t, s, "SELECT id FROM "+ks+".many", tc.limit) + if len(r.Rows) != tc.rows || r.Truncated != tc.truncated { + t.Errorf("limit %d: %d rows, truncated %v", tc.limit, len(r.Rows), r.Truncated) + } + } + + // Statements without rows. + r = run(t, s, "INSERT INTO "+ks+".many (id, v) VALUES (500, 1)", 10) + if r.Columns != nil || len(r.Rows) != 0 { + t.Errorf("insert: %+v", r) + } + // A conditional write answers with [applied]. + r = run(t, s, "INSERT INTO "+ks+".many (id, v) VALUES (500, 2) IF NOT EXISTS", 10) + if r.Columns[0].Name != "[applied]" || *r.Rows[0][0] != "false" { + t.Errorf("conditional: %+v %q", r.Columns, texts(r.Rows)) + } + // A batch is one statement. + run(t, s, `BEGIN BATCH + INSERT INTO `+ks+`.many (id, v) VALUES (501, 1); + INSERT INTO `+ks+`.many (id, v) VALUES (502, 1); + APPLY BATCH`, 0) + r = run(t, s, "SELECT count(*) FROM "+ks+".many WHERE id IN (501, 502)", 10) + if got := firstRow(t, r); !reflect.DeepEqual(got, []string{"2"}) { + t.Errorf("batch: %q", got) + } + + // Errors carry the server's code; a syntax error has a position. + err := execErr(t, s, "SELECT * FROM "+ks+".nope") + if err.Kind != apperr.Database || err.Code != "Invalid" { + t.Errorf("unknown table: %+v", err) + } + bad := "SELEC * FROM " + ks + ".t" + err = execErr(t, s, bad) + if err.Code != "SyntaxError" || err.Position == nil || *err.Position < 0 || *err.Position >= len(bad) { + t.Errorf("syntax error: %+v", err) + } + + // USE sticks to the session. + run(t, s, "USE "+ks, 0) + if cs := s.CurrentSchema(); cs == nil || *cs != ks { + t.Errorf("current schema: %v", cs) + } + r = run(t, s, "SELECT count(*) FROM c", 10) + if got := firstRow(t, r); !reflect.DeepEqual(got, []string{"1"}) { + t.Errorf("after USE: %q", got) + } + if err := execErr(t, s, "USE lq_go_no_such_keyspace"); err.Code != "Invalid" { + t.Errorf("USE of a missing keyspace: %+v", err) + } + + // Warnings of the server come back as notices (Cassandra 4.0 and later + // warn about aggregations without a partition key). + r = run(t, s, "SELECT count(*) FROM "+ks+".many", 10) + if got := firstRow(t, r); !reflect.DeepEqual(got, []string{"123"}) { + t.Errorf("count: %q", got) + } + if !strings.Contains(s.ServerVersion(), "Cassandra 3.") { + found := false + for _, n := range r.Notices { + if strings.HasPrefix(n, "WARNING: ") && strings.Contains(n, "partition key") { + found = true + } + } + if !found { + t.Errorf("notices: %q", r.Notices) + } + } + + // A filtering scan works. + r = run(t, s, "SELECT * FROM "+ks+".many WHERE v = 5 ALLOW FILTERING", 10) + if len(r.Rows) != 1 { + t.Errorf("filtering: %d rows", len(r.Rows)) + } + + if strings.Contains(s.ServerVersion(), "Cassandra 5") { + run(t, s, "CREATE TABLE "+ks+".vec (id int PRIMARY KEY, e vector)", 0) + run(t, s, "INSERT INTO "+ks+".vec (id, e) VALUES (1, [0.5, 1.5, -2])", 0) + r := run(t, s, "SELECT e FROM "+ks+".vec", 10) + if r.Columns[0].TypeName != "vector" { + t.Errorf("vector type: %s", r.Columns[0].TypeName) + } + if got := firstRow(t, r); !reflect.DeepEqual(got, []string{"[0.5, 1.5, -2]"}) { + t.Errorf("vector: %q", got) + } + } +} + +func TestCassandraSchemaDDLAndStream(t *testing.T) { + s := cassSession(t) + ctx := context.Background() + ks := keyspace(t, s, "lq_go_schema") + run(t, s, "CREATE TYPE "+ks+".addr (street text, zip int)", 0) + run(t, s, `CREATE TABLE `+ks+`."Items" ( + tenant text, day date, seq int, "Name" text, tags set, home frozen, + total decimal static, + PRIMARY KEY ((tenant, day), seq) + ) WITH CLUSTERING ORDER BY (seq DESC) AND comment = 'it''s here' + AND gc_grace_seconds = 3600`, 0) + run(t, s, `CREATE INDEX lq_items_name ON `+ks+`."Items" ("Name")`, 0) + // User-defined functions are off unless cassandra.yaml enables them. + _, ferr := s.Execute(ctx, model.ExecRequest{SQL: "CREATE FUNCTION " + ks + ".plus (a int, b int) " + + "CALLED ON NULL INPUT RETURNS int LANGUAGE java AS 'return a + b;'"}) + functions := ferr == nil + + schemas, err := s.ListSchemas(ctx) + if err != nil { + t.Fatal(err) + } + user, system := -1, -1 + for i, n := range schemas { + switch n { + case ks: + user = i + case "system": + system = i + } + } + if user < 0 || system < 0 || user > system { + t.Errorf("user keyspaces come first: %q", schemas) + } + + objects, err := s.ListObjects(ctx, ks) + if err != nil { + t.Fatal(err) + } + has := func(kind, name string) bool { + for _, o := range objects { + if o.Kind == kind && o.Name == name { + return true + } + } + return false + } + if !has("table", "Items") || !has("type", "addr") || !has("index", "lq_items_name") { + t.Errorf("objects: %+v", objects) + } + if functions && !has("function", "plus(int, int)") { + t.Errorf("objects: %+v", objects) + } + + columns, err := s.ListColumns(ctx, ks, "Items") + if err != nil { + t.Fatal(err) + } + var shape [][3]string + for _, c := range columns { + shape = append(shape, [3]string{c.Name, *c.KeyRole, strconv.FormatBool(c.PrimaryKey)}) + } + wantShape := [][3]string{ + {"tenant", "partition", "true"}, + {"day", "partition", "true"}, + {"seq", "clustering", "true"}, + {"total", "static", "false"}, + {"Name", "regular", "false"}, + {"home", "regular", "false"}, + {"tags", "regular", "false"}, + } + if !reflect.DeepEqual(shape, wantShape) { + t.Fatalf("columns: %v", shape) + } + if columns[5].TypeName != "frozen" || columns[6].TypeName != "set" { + t.Errorf("types: %s, %s", columns[5].TypeName, columns[6].TypeName) + } + + // The table's DDL recreates it, indexes included. + ddl, err := s.ObjectDDL(ctx, ks, "Items", "table") + if err != nil { + t.Fatal(err) + } + for _, part := range []string{ + "CREATE TABLE " + ks + `."Items" (`, + "total decimal static", + "PRIMARY KEY ((tenant, day), seq)", + "CLUSTERING ORDER BY (seq DESC)", + "comment = 'it''s here'", + "CREATE INDEX lq_items_name ON", + } { + if !strings.Contains(ddl, part) { + t.Errorf("%q not in\n%s", part, ddl) + } + } + run(t, s, "DROP TABLE "+ks+`."Items"`, 0) + for _, statement := range fixtures.Statements(ddl, "cassandra") { + run(t, s, statement, 0) + } + again, err := s.ListColumns(ctx, ks, "Items") + if err != nil { + t.Fatal(err) + } + a, _ := json.Marshal(again) + b, _ := json.Marshal(columns) + if string(a) != string(b) { + t.Errorf("recreated columns:\n%s\n%s", a, b) + } + + ddl, err = s.ObjectDDL(ctx, ks, "addr", "type") + if err != nil || !strings.Contains(ddl, "CREATE TYPE "+ks+".addr (") { + t.Errorf("type DDL: %v\n%s", err, ddl) + } + ddl, err = s.ObjectDDL(ctx, ks, "lq_items_name", "index") + if err != nil || !strings.HasPrefix(ddl, "CREATE INDEX lq_items_name ON "+ks+`."Items"`) { + t.Errorf("index DDL: %v\n%s", err, ddl) + } + if functions { + ddl, err := s.ObjectDDL(ctx, ks, "plus(int, int)", "function") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(ddl, "CREATE OR REPLACE FUNCTION "+ks+".plus (a int, b int)") || + !strings.Contains(ddl, "$$return a + b;$$") { + t.Errorf("function DDL:\n%s", ddl) + } + run(t, s, "DROP FUNCTION "+ks+".plus(int, int)", 0) + run(t, s, ddl, 0) + } + ddl, err = s.ObjectDDL(ctx, ks, ks, "keyspace") + if err != nil || !strings.HasPrefix(ddl, "CREATE KEYSPACE "+ks+" WITH replication = {") { + t.Errorf("keyspace DDL: %v\n%s", err, ddl) + } + if _, err := s.ObjectDDL(ctx, ks, "x", "sequence"); err == nil { + t.Error("sequence DDL accepted") + } + + // Materialized views exist only where the server enables them. + run(t, s, "CREATE TABLE "+ks+".base (id int, day int, v text, PRIMARY KEY (id, day))", 0) + _, verr := s.Execute(ctx, model.ExecRequest{SQL: "CREATE MATERIALIZED VIEW " + ks + ".by_day AS SELECT * FROM " + + ks + ".base WHERE day IS NOT NULL AND id IS NOT NULL PRIMARY KEY (day, id)"}) + if verr == nil { + objects, err := s.ListObjects(ctx, ks) + if err != nil { + t.Fatal(err) + } + found := false + for _, o := range objects { + found = found || (o.Kind == "matview" && o.Name == "by_day") + } + if !found { + t.Errorf("objects: %+v", objects) + } + ddl, err := s.ObjectDDL(ctx, ks, "by_day", "matview") + if err != nil || !strings.Contains(ddl, "CREATE MATERIALIZED VIEW "+ks+".by_day AS") || + !strings.Contains(ddl, "PRIMARY KEY (day, id)") { + t.Errorf("view DDL: %v\n%s", err, ddl) + } + run(t, s, "INSERT INTO "+ks+".base (id, day, v) VALUES (1, 2, 'x')", 0) + r := run(t, s, "SELECT * FROM "+ks+".by_day", 10) + if r.Editable != nil || r.ReadOnlyReason == nil { + t.Errorf("view editable: %+v", r.Editable) + } + } + + // Streaming reads every row, a page at a time. + for i := 0; i < 1200; i++ { + run(t, s, fmt.Sprintf("INSERT INTO %s.base (id, day, v) VALUES (%d, 1, 'v%d')", ks, i, i), 0) + } + sink := make(chan drivers.StreamEvent, 4) + counted := make(chan [2]int) + go func() { + columns, rows := 0, 0 + for ev := range sink { + if ev.Columns != nil { + columns = len(ev.Columns) + } + rows += len(ev.Rows) + } + counted <- [2]int{columns, rows} + }() + total, err := s.Stream(ctx, "SELECT id, day, v FROM "+ks+".base", sink) + close(sink) + if err != nil { + t.Fatal(err) + } + if got := <-counted; total != 1200 || got != [2]int{3, 1200} { + t.Errorf("stream: total %d, got %v", total, got) + } + // A reader that goes away stops the stream. + stopCtx, stop := context.WithCancel(ctx) + sink = make(chan drivers.StreamEvent) + go func() { + <-sink + stop() + }() + _, err = s.Stream(stopCtx, "SELECT id FROM "+ks+".base", sink) + if apperr.From(err).Kind != apperr.Cancelled { + t.Errorf("stopped stream: %v", err) + } + if _, err := s.Stream(ctx, "INSERT INTO "+ks+".base (id, day, v) VALUES (0, 0, 'x')", make(chan drivers.StreamEvent, 1)); err == nil { + t.Error("a statement without rows streamed") + } +} + +func TestCassandraResultEditing(t *testing.T) { + s := cassSession(t) + ctx := context.Background() + ks := keyspace(t, s, "lq_go_edit") + run(t, s, `CREATE TABLE `+ks+`.items (tenant text, day date, seq int, name text, tags set, + PRIMARY KEY (tenant, day, seq))`, 0) + run(t, s, `INSERT INTO `+ks+`.items (tenant, day, seq, name, tags) + VALUES ('a', '2024-05-06', 1, 'one', {'x'})`, 0) + run(t, s, `INSERT INTO `+ks+`.items (tenant, day, seq, name, tags) + VALUES ('a', '2024-05-06', 2, 'two', null)`, 0) + + r := run(t, s, "SELECT tenant, day, seq, name, tags FROM "+ks+".items", 100) + if r.ReadOnlyReason != nil { + t.Fatalf("read-only: %s", *r.ReadOnlyReason) + } + target := r.Editable + if target == nil { + t.Fatal("not editable") + } + if *target.Schema != ks || target.Table != "items" || !reflect.DeepEqual(target.Key, []int{0, 1, 2}) || + target.Columns[4].TypeName != "set" { + t.Fatalf("target: %+v", target) + } + + // Without the whole key, with an alias, or from system tables: read-only. + r = run(t, s, "SELECT tenant, name FROM "+ks+".items", 100) + if r.Editable != nil || r.ReadOnlyReason == nil || !strings.Contains(*r.ReadOnlyReason, "primary key") { + t.Errorf("partial key: %v", r.ReadOnlyReason) + } + r = run(t, s, "SELECT tenant, day, seq, name AS n FROM "+ks+".items", 100) + if r.Editable != nil { + t.Error("alias editable") + } + r = run(t, s, "SELECT keyspace_name FROM system_schema.keyspaces", 100) + if r.Editable != nil || r.ReadOnlyReason == nil { + t.Error("system table editable") + } + + key := func(seq string) []*string { + return []*string{model.Str("a"), model.Str("2024-05-06"), model.Str(seq)} + } + value := func(column int, v string) model.CellValue { + return model.CellValue{Column: column, Value: model.Str(v)} + } + saved, err := s.ApplyChanges(ctx, model.ApplyRequest{Target: *target, Changes: []model.RowChange{ + {Op: model.OpUpdate, Key: key("1"), Values: []model.CellValue{value(3, "it's one"), value(4, "{'x', 'y'}")}}, + {Op: model.OpDelete, Key: key("2")}, + {Op: model.OpInsert, Values: []model.CellValue{value(0, "b"), value(1, "2024-05-07"), value(2, "3"), value(3, "three")}}, + }}) + if err != nil { + t.Fatal(err) + } + if saved.Updated != 1 || saved.Deleted != 1 || saved.Inserted != 1 || saved.InTransaction { + t.Errorf("saved: %+v", saved) + } + rows := texts(run(t, s, "SELECT seq, name, tags FROM "+ks+".items", 100).Rows) + sort.Slice(rows, func(i, j int) bool { return rows[i][0] < rows[j][0] }) + if want := [][]string{{"1", "it's one", "{'x', 'y'}"}, {"3", "three", ""}}; !reflect.DeepEqual(rows, want) { + t.Errorf("rows: %q", rows) + } + + // A batch the server refuses changes nothing. + _, err = s.ApplyChanges(ctx, model.ApplyRequest{Target: *target, Changes: []model.RowChange{ + {Op: model.OpDelete, Key: key("1")}, + {Op: model.OpDelete, Key: []*string{model.Str("a"), model.Str("not a date"), model.Str("1")}}, + }}) + if err == nil { + t.Error("bad batch accepted") + } + r = run(t, s, "SELECT count(*) FROM "+ks+".items", 10) + if got := firstRow(t, r); !reflect.DeepEqual(got, []string{"2"}) { + t.Errorf("count after a refused batch: %q", got) + } +} + +func TestCassandraDDLFixtures(t *testing.T) { + s := cassSession(t) + ks := keyspace(t, s, "lq_go_cql") + fixtures.CheckDDL(t, s, "cassandra", ks) +} + +func TestCassandraCancelStopsWaiting(t *testing.T) { + s := cassSession(t) + ctx := context.Background() + // Nothing runs: cancel is harmless. + if err := s.Cancel(ctx); err != nil { + t.Fatal(err) + } + ks := keyspace(t, s, "lq_go_cancel") + run(t, s, "CREATE TABLE "+ks+".t (id int PRIMARY KEY, v int)", 0) + done := make(chan error, 1) + go func() { + // Statements in a row, so one is in flight when the cancel comes. + for i := 0; i < 100_000; i++ { + sql := fmt.Sprintf("INSERT INTO %s.t (id, v) VALUES (%d, 1)", ks, i) + if _, err := s.Execute(ctx, model.ExecRequest{SQL: sql}); err != nil { + done <- err + return + } + } + done <- nil + }() + // Cancel only acts on a request in flight: keep asking until one stops. + var err error +wait: + for { + select { + case err = <-done: + break wait + case <-time.After(50 * time.Millisecond): + _ = s.Cancel(ctx) + } + } + if err == nil || apperr.From(err).Kind != apperr.Cancelled { + t.Fatalf("not cancelled: %v", err) + } + // The session still works. + run(t, s, "SELECT count(*) FROM "+ks+".t", 10) +} diff --git a/internal/drivers/cassandra/values.go b/internal/drivers/cassandra/values.go new file mode 100644 index 0000000..3b3ea66 --- /dev/null +++ b/internal/drivers/cassandra/values.go @@ -0,0 +1,920 @@ +package cassandra + +import ( + "encoding/binary" + "encoding/hex" + "fmt" + "math" + "math/big" + "math/bits" + "net/netip" + "strconv" + "strings" + "unicode" + + gocql "github.com/apache/cassandra-gocql-driver/v2" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +// kindVector and kindUnknown extend gocql's type ids: vectors and unknown +// custom types both arrive as TypeCustom. +const ( + kindVector gocql.Type = -1 + kindUnknown gocql.Type = -2 +) + +// ctype is a column type as the values are decoded here, built once per +// result column from the driver's TypeInfo. Values are read from their wire +// bytes, so collections keep the order the server sent and every digit of +// varint and decimal survives. +type ctype struct { + kind gocql.Type + // list, set, vector: [element]; map: [key, value]; tuple: its items; + // UDT: its fields. + elems []*ctype + // UDT field names. + fields []string + // UDT name. + name string + // Vector dimensions. + dims int +} + +// typeOf converts the driver's type description. +func typeOf(info gocql.TypeInfo) *ctype { + switch t := info.(type) { + case gocql.CollectionType: + switch t.Type() { + case gocql.TypeMap: + return &ctype{kind: gocql.TypeMap, elems: []*ctype{typeOf(t.Key), typeOf(t.Elem)}} + case gocql.TypeList, gocql.TypeSet: + return &ctype{kind: t.Type(), elems: []*ctype{typeOf(t.Elem)}} + } + case gocql.TupleTypeInfo: + out := &ctype{kind: gocql.TypeTuple} + for _, e := range t.Elems { + out.elems = append(out.elems, typeOf(e)) + } + return out + case gocql.UDTTypeInfo: + out := &ctype{kind: gocql.TypeUDT, name: t.Name} + for _, f := range t.Elements { + out.fields = append(out.fields, f.Name) + out.elems = append(out.elems, typeOf(f.Type)) + } + return out + case gocql.VectorType: + return &ctype{kind: kindVector, elems: []*ctype{typeOf(t.SubType)}, dims: t.Dimensions} + case nil: + return &ctype{kind: kindUnknown} + } + if _, ok := nativeNames[info.Type()]; ok { + return &ctype{kind: info.Type()} + } + return &ctype{kind: kindUnknown} +} + +var nativeNames = map[gocql.Type]string{ + gocql.TypeAscii: "ascii", + gocql.TypeBoolean: "boolean", + gocql.TypeBlob: "blob", + gocql.TypeCounter: "counter", + gocql.TypeDate: "date", + gocql.TypeDecimal: "decimal", + gocql.TypeDouble: "double", + gocql.TypeDuration: "duration", + gocql.TypeFloat: "float", + gocql.TypeInt: "int", + gocql.TypeBigInt: "bigint", + gocql.TypeText: "text", + gocql.TypeVarchar: "text", + gocql.TypeTimestamp: "timestamp", + gocql.TypeInet: "inet", + gocql.TypeSmallInt: "smallint", + gocql.TypeTinyInt: "tinyint", + gocql.TypeTime: "time", + gocql.TypeTimeUUID: "timeuuid", + gocql.TypeUUID: "uuid", + gocql.TypeVarint: "varint", +} + +// typeName is the type as system_schema writes it: list, +// map, vector, a UDT by its name. Result metadata does +// not say which collections and UDTs are frozen. +func typeName(t *ctype) string { + switch t.kind { + case gocql.TypeList: + return "list<" + typeName(t.elems[0]) + ">" + case gocql.TypeSet: + return "set<" + typeName(t.elems[0]) + ">" + case gocql.TypeMap: + return "map<" + typeName(t.elems[0]) + ", " + typeName(t.elems[1]) + ">" + case kindVector: + return "vector<" + typeName(t.elems[0]) + ", " + strconv.Itoa(t.dims) + ">" + case gocql.TypeUDT: + return quoteName(t.name) + case gocql.TypeTuple: + names := make([]string, len(t.elems)) + for i, e := range t.elems { + names[i] = typeName(e) + } + return "tuple<" + strings.Join(names, ", ") + ">" + } + if n, ok := nativeNames[t.kind]; ok { + return n + } + return "custom" +} + +func columnKind(t *ctype) model.ValueKind { + switch t.kind { + case gocql.TypeTinyInt, gocql.TypeSmallInt, gocql.TypeInt, gocql.TypeBigInt, gocql.TypeVarint, + gocql.TypeDecimal, gocql.TypeFloat, gocql.TypeDouble, gocql.TypeCounter: + return model.KindNumber + case gocql.TypeBoolean: + return model.KindBool + case gocql.TypeTimestamp, gocql.TypeDate, gocql.TypeTime, gocql.TypeDuration: + return model.KindTemporal + case gocql.TypeBlob: + return model.KindBinary + case gocql.TypeText, gocql.TypeVarchar, gocql.TypeAscii, gocql.TypeUUID, gocql.TypeTimeUUID, gocql.TypeInet: + return model.KindText + } + return model.KindOther +} + +func isText(t *ctype) bool { + return t.kind == gocql.TypeText || t.kind == gocql.TypeVarchar || t.kind == gocql.TypeAscii +} + +// rawCell receives a column's bytes as they came from the server; nil is +// null. The bytes belong to the driver's frame: they are copied only when a +// row outlives the next Scan. +type rawCell struct{ data []byte } + +func (c *rawCell) UnmarshalCQL(_ gocql.TypeInfo, data []byte) error { + c.data = data + return nil +} + +// rowReader scans rows as raw bytes. gocql spreads a tuple column over one +// destination per item; the reader joins them back into the tuple's wire +// form, so every column is decoded the same way. +type rowReader struct { + types []*ctype + // Number of destinations of each column: 1, or the items of a tuple. + widths []int + cells []rawCell + dest []any +} + +func newRowReader(cols []gocql.ColumnInfo) *rowReader { + r := &rowReader{} + for _, c := range cols { + t := typeOf(c.TypeInfo) + r.types = append(r.types, t) + width := 1 + if _, ok := c.TypeInfo.(gocql.TupleTypeInfo); ok { + width = len(t.elems) + } + r.widths = append(r.widths, width) + } + total := 0 + for _, w := range r.widths { + total += w + } + r.cells = make([]rawCell, total) + r.dest = make([]any, total) + for i := range r.cells { + r.dest[i] = &r.cells[i] + } + return r +} + +// values returns the bytes of each column of the scanned row. A tuple whose +// items are all null is read as a null tuple: gocql does not tell them +// apart. +func (r *rowReader) values(copyBytes bool) [][]byte { + out := make([][]byte, len(r.types)) + pos := 0 + for i, t := range r.types { + if t.kind == gocql.TypeTuple && r.widths[i] == len(t.elems) { + items := r.cells[pos : pos+r.widths[i]] + pos += r.widths[i] + allNull := true + for _, c := range items { + if c.data != nil { + allNull = false + } + } + if allNull { + continue + } + buf := []byte{} + for _, c := range items { + buf = appendBytes(buf, c.data) + } + out[i] = buf + continue + } + data := r.cells[pos].data + pos++ + if copyBytes && data != nil { + data = append([]byte{}, data...) + } + out[i] = data + } + return out +} + +// appendBytes writes a [bytes] value: its length, -1 for null, then the +// bytes. +func appendBytes(buf, data []byte) []byte { + if data == nil { + return binary.BigEndian.AppendUint32(buf, math.MaxUint32) + } + buf = binary.BigEndian.AppendUint32(buf, uint32(len(data))) + return append(buf, data...) +} + +// cellText is a value as the grid shows it: text as it is, temporal values +// and addresses unquoted, blobs cut to limit bytes, everything else as its +// CQL literal (collections and UDTs as valid CQL literals). nil is null. +func cellText(t *ctype, data []byte, limit int) (*string, error) { + if data == nil { + return nil, nil + } + var s string + var err error + switch { + case isText(t): + s = string(data) + case t.kind == gocql.TypeBlob: + s = blob(data, limit) + case len(data) == 0: + // An empty value of a type that has no empty form. + s = "" + case t.kind == gocql.TypeTimestamp || t.kind == gocql.TypeDate || t.kind == gocql.TypeTime || + t.kind == gocql.TypeInet: + s, err = plain(t, data) + default: + s, err = literal(t, data) + } + if err != nil { + return nil, err + } + return &s, nil +} + +func badValue(t *ctype, data []byte) error { + return apperr.Internalf("A %s value of %d bytes cannot be read.", typeName(t), len(data)) +} + +// plain is the text of a temporal value or an address, unquoted. +func plain(t *ctype, data []byte) (string, error) { + switch t.kind { + case gocql.TypeTimestamp: + if len(data) != 8 { + return "", badValue(t, data) + } + return timestampText(int64(binary.BigEndian.Uint64(data))), nil + case gocql.TypeDate: + if len(data) != 4 { + return "", badValue(t, data) + } + return dateText(int64(binary.BigEndian.Uint32(data)) - (1 << 31)), nil + case gocql.TypeTime: + if len(data) != 8 { + return "", badValue(t, data) + } + return timeText(int64(binary.BigEndian.Uint64(data))), nil + case gocql.TypeInet: + switch len(data) { + case 4: + return netip.AddrFrom4([4]byte(data)).String(), nil + case 16: + return netip.AddrFrom16([16]byte(data)).String(), nil + } + return "", badValue(t, data) + } + return "", nil +} + +// blob is 0x00ff, cut to limit bytes with the full size noted. +func blob(data []byte, limit int) string { + shown := data + if len(shown) > limit { + shown = shown[:limit] + } + s := "0x" + hex.EncodeToString(shown) + if len(data) > len(shown) { + s += fmt.Sprintf("… (%d bytes)", len(data)) + } + return s +} + +// literal is a value as a CQL literal, as it is written inside a +// collection. nil is null. +func literal(t *ctype, data []byte) (string, error) { + if data == nil { + return "null", nil + } + if isText(t) { + return quoteStr(string(data)), nil + } + if t.kind == gocql.TypeBlob { + return blob(data, math.MaxInt), nil + } + if len(data) == 0 { + // An empty value of a type that has no empty form. + return "null", nil + } + fixed := func(n int) error { + if len(data) != n { + return badValue(t, data) + } + return nil + } + switch t.kind { + case gocql.TypeBoolean: + if err := fixed(1); err != nil { + return "", err + } + return strconv.FormatBool(data[0] != 0), nil + case gocql.TypeTinyInt: + if err := fixed(1); err != nil { + return "", err + } + return strconv.Itoa(int(int8(data[0]))), nil + case gocql.TypeSmallInt: + if err := fixed(2); err != nil { + return "", err + } + return strconv.Itoa(int(int16(binary.BigEndian.Uint16(data)))), nil + case gocql.TypeInt: + if err := fixed(4); err != nil { + return "", err + } + return strconv.Itoa(int(int32(binary.BigEndian.Uint32(data)))), nil + case gocql.TypeBigInt, gocql.TypeCounter: + if err := fixed(8); err != nil { + return "", err + } + return strconv.FormatInt(int64(binary.BigEndian.Uint64(data)), 10), nil + case gocql.TypeFloat: + if err := fixed(4); err != nil { + return "", err + } + return floatText(float64(math.Float32frombits(binary.BigEndian.Uint32(data))), 32), nil + case gocql.TypeDouble: + if err := fixed(8); err != nil { + return "", err + } + return floatText(math.Float64frombits(binary.BigEndian.Uint64(data)), 64), nil + case gocql.TypeVarint: + return integerText(data), nil + case gocql.TypeDecimal: + if len(data) < 4 { + return "", badValue(t, data) + } + scale := int32(binary.BigEndian.Uint32(data)) + return decimalText(integerText(data[4:]), scale), nil + case gocql.TypeUUID, gocql.TypeTimeUUID: + if err := fixed(16); err != nil { + return "", err + } + return uuidText(data), nil + case gocql.TypeTimestamp, gocql.TypeDate, gocql.TypeTime, gocql.TypeInet: + s, err := plain(t, data) + if err != nil { + return "", err + } + return quoteStr(s), nil + case gocql.TypeDuration: + months, n, err := readVInt(data) + if err != nil { + return "", badValue(t, data) + } + days, m, err := readVInt(data[n:]) + if err != nil { + return "", badValue(t, data) + } + nanos, _, err := readVInt(data[n+m:]) + if err != nil { + return "", badValue(t, data) + } + return durationText(int32(months), int32(days), nanos), nil + case gocql.TypeList, gocql.TypeSet: + items, err := collectionItems(t, data, 1) + if err != nil { + return "", err + } + if t.kind == gocql.TypeList { + return "[" + strings.Join(items, ", ") + "]", nil + } + return "{" + strings.Join(items, ", ") + "}", nil + case gocql.TypeMap: + items, err := collectionItems(t, data, 2) + if err != nil { + return "", err + } + pairs := make([]string, 0, len(items)/2) + for i := 0; i+1 < len(items); i += 2 { + pairs = append(pairs, items[i]+": "+items[i+1]) + } + return "{" + strings.Join(pairs, ", ") + "}", nil + case kindVector: + items, err := vectorItems(t, data) + if err != nil { + return "", err + } + return "[" + strings.Join(items, ", ") + "]", nil + case gocql.TypeTuple: + items, err := sequenceItems(t, data) + if err != nil { + return "", err + } + return "(" + strings.Join(items, ", ") + ")", nil + case gocql.TypeUDT: + items, err := sequenceItems(t, data) + if err != nil { + return "", err + } + for i := range items { + items[i] = quoteName(t.fields[i]) + ": " + items[i] + } + return "{" + strings.Join(items, ", ") + "}", nil + } + // A custom type the driver does not know: its bytes. + return blob(data, math.MaxInt), nil +} + +// reader walks the [bytes] values of a collection, tuple or UDT. +type reader struct { + data []byte + bad bool +} + +func (r *reader) int32() int32 { + if len(r.data) < 4 { + r.bad = true + return 0 + } + n := int32(binary.BigEndian.Uint32(r.data)) + r.data = r.data[4:] + return n +} + +// bytes reads one [bytes] value; nil is null. +func (r *reader) bytes() []byte { + n := r.int32() + if r.bad || n < 0 { + return nil + } + if int(n) > len(r.data) { + r.bad = true + return nil + } + out := r.data[:n] + r.data = r.data[n:] + return out +} + +// collectionItems reads a list or set (per = 1) or a map (per = 2, keys and +// values alternate) as literals. +func collectionItems(t *ctype, data []byte, per int) ([]string, error) { + r := &reader{data: data} + n := r.int32() + if r.bad || n < 0 { + return nil, badValue(t, data) + } + var out []string + for i := 0; i < int(n); i++ { + for j := 0; j < per; j++ { + v := r.bytes() + if r.bad { + return nil, badValue(t, data) + } + s, err := literal(t.elems[j], v) + if err != nil { + return nil, err + } + out = append(out, s) + } + } + return out, nil +} + +// sequenceItems reads the items of a tuple or the fields of a UDT; the ones +// missing at the end are null. +func sequenceItems(t *ctype, data []byte) ([]string, error) { + r := &reader{data: data} + out := make([]string, len(t.elems)) + for i, e := range t.elems { + var v []byte + if len(r.data) > 0 { + v = r.bytes() + if r.bad { + return nil, badValue(t, data) + } + } + s, err := literal(e, v) + if err != nil { + return nil, err + } + out[i] = s + } + return out, nil +} + +// vectorItems reads a vector: fixed-size items one after the other, +// variable-size ones each behind its length, as gocql writes them. +func vectorItems(t *ctype, data []byte) ([]string, error) { + sub := t.elems[0] + out := make([]string, 0, t.dims) + if t.dims <= 0 { + return out, nil + } + variable := vectorVariable(sub) + size := len(data) / t.dims + for i := 0; i < t.dims; i++ { + if variable { + n, used, err := readUVInt(data) + if err != nil || uint64(len(data)-used) < n { + return nil, badValue(t, data) + } + size = int(n) + data = data[used:] + } + if len(data) < size { + return nil, badValue(t, data) + } + s, err := literal(sub, data[:size]) + if err != nil { + return nil, err + } + out = append(out, s) + data = data[size:] + } + return out, nil +} + +func vectorVariable(t *ctype) bool { + switch t.kind { + case gocql.TypeBigInt, gocql.TypeBoolean, gocql.TypeTimestamp, gocql.TypeDouble, gocql.TypeFloat, + gocql.TypeInt, gocql.TypeTimeUUID, gocql.TypeUUID: + return false + case kindVector: + return vectorVariable(t.elems[0]) + } + return true +} + +// readUVInt reads Cassandra's unsigned variable-length integer: the leading +// one bits of the first byte count the bytes that follow. +func readUVInt(data []byte) (uint64, int, error) { + if len(data) == 0 { + return 0, 0, fmt.Errorf("unexpected end of value") + } + first := data[0] + extra := bits.LeadingZeros8(^first) + if len(data) < extra+1 { + return 0, 0, fmt.Errorf("unexpected end of value") + } + var v uint64 + if extra < 8 { + v = uint64(first & (0xff >> extra)) + } + for i := 1; i <= extra; i++ { + v = v<<8 | uint64(data[i]) + } + return v, extra + 1, nil +} + +// readVInt reads a signed (zigzag) variable-length integer. +func readVInt(data []byte) (int64, int, error) { + u, n, err := readUVInt(data) + if err != nil { + return 0, 0, err + } + return int64(u>>1) ^ -int64(u&1), n, nil +} + +func uuidText(b []byte) string { + h := hex.EncodeToString(b) + return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32] +} + +// floatText is the shortest round-trip text; very large or small magnitudes +// use an exponent (1.5e300, 1e-7). +func floatText(v float64, size int) string { + switch { + case math.IsNaN(v): + return "NaN" + case math.IsInf(v, 1): + return "Infinity" + case math.IsInf(v, -1): + return "-Infinity" + case v != 0 && (math.Abs(v) >= 1e16 || math.Abs(v) < 1e-5): + s := strconv.FormatFloat(v, 'e', -1, size) + mantissa, exp, _ := strings.Cut(s, "e") + neg := strings.HasPrefix(exp, "-") + exp = strings.TrimLeft(exp, "+-") + exp = strings.TrimLeft(exp, "0") + if exp == "" { + exp = "0" + } + if neg { + exp = "-" + exp + } + return mantissa + "e" + exp + } + return strconv.FormatFloat(v, 'f', -1, size) +} + +// integerText is the decimal text of a two's complement big-endian integer. +func integerText(b []byte) string { + if len(b) == 0 { + return "0" + } + n := new(big.Int).SetBytes(b) + if b[0]&0x80 != 0 { + n.Sub(n, new(big.Int).Lsh(big.NewInt(1), uint(8*len(b)))) + } + return n.String() +} + +// decimalText writes unscaled × 10^-scale the way Java's +// BigDecimal.toString does: plain when the exponent allows, scientific +// otherwise. +func decimalText(unscaled string, scale int32) string { + sign, digits := "", unscaled + if strings.HasPrefix(unscaled, "-") { + sign, digits = "-", unscaled[1:] + } + adjusted := -int64(scale) + int64(len(digits)) - 1 + if scale == 0 { + return unscaled + } + if scale > 0 && adjusted >= -6 { + s := int(scale) + if len(digits) > s { + return sign + digits[:len(digits)-s] + "." + digits[len(digits)-s:] + } + return sign + "0." + strings.Repeat("0", s-len(digits)) + digits + } + mantissa := digits[:1] + if len(digits) > 1 { + mantissa += "." + digits[1:] + } + exp := strconv.FormatInt(adjusted, 10) + if adjusted >= 0 { + exp = "+" + exp + } + return sign + mantissa + "E" + exp +} + +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 } + +// civilFromDays is the year, month and day of a day count since +// 1970-01-01. +func civilFromDays(days int64) (int64, int64, int64) { + z := days + 719_468 + era := floorDiv(z, 146_097) + doe := floorMod(z, 146_097) + yoe := (doe - doe/1460 + doe/36_524 - doe/146_096) / 365 + doy := doe - (365*yoe + yoe/4 - yoe/100) + mp := (5*doy + 2) / 153 + day := doy - (153*mp+2)/5 + 1 + month := mp + 3 + if mp >= 10 { + month = mp - 9 + } + year := yoe + era*400 + if month <= 2 { + year++ + } + return year, month, day +} + +func dateText(days int64) string { + y, m, d := civilFromDays(days) + if y < 0 { + return fmt.Sprintf("-%04d-%02d-%02d", -y, m, d) + } + return fmt.Sprintf("%04d-%02d-%02d", y, m, d) +} + +// timestampText is 2024-05-06 07:08:09.123+0000. +func timestampText(millis int64) string { + secs := floorDiv(millis, 1000) + ms := floorMod(millis, 1000) + day := floorDiv(secs, 86_400) + tod := floorMod(secs, 86_400) + return fmt.Sprintf("%s %02d:%02d:%02d.%03d+0000", dateText(day), tod/3600, tod%3600/60, tod%60, ms) +} + +// timeText is 07:08:09.123456789. +func timeText(nanos int64) string { + secs := floorDiv(nanos, 1_000_000_000) + frac := floorMod(nanos, 1_000_000_000) + return fmt.Sprintf("%02d:%02d:%02d.%09d", secs/3600, secs%3600/60, secs%60, frac) +} + +// durationText is 1y2mo3d4h5m6s7ms8us9ns, the form CQL reads back. +func durationText(months, days int32, nanos int64) string { + negative := months < 0 || days < 0 || nanos < 0 + abs := func(v int64) uint64 { + if v < 0 { + return uint64(-v) + } + return uint64(v) + } + mo, d, ns := abs(int64(months)), abs(int64(days)), abs(nanos) + var b strings.Builder + put := func(n uint64, unit string) { + if n > 0 { + b.WriteString(strconv.FormatUint(n, 10)) + b.WriteString(unit) + } + } + put(mo/12, "y") + put(mo%12, "mo") + put(d, "d") + put(ns/3_600_000_000_000, "h") + put(ns/60_000_000_000%60, "m") + put(ns/1_000_000_000%60, "s") + put(ns/1_000_000%1000, "ms") + put(ns/1000%1000, "us") + put(ns%1000, "ns") + out := b.String() + if out == "" { + out = "0s" + } + if negative { + out = "-" + out + } + return out +} + +// reserved holds CQL's reserved words (Cassandra 3.0 to 5.0): they need +// quotes as names. +var reserved = map[string]bool{} + +func init() { + for _, w := range strings.Fields(`ADD ALLOW ALTER AND APPLY ASC AUTHORIZE BATCH BEGIN BY + COLUMNFAMILY CREATE DEFAULT DELETE DESC DESCRIBE DROP ENTRIES EXECUTE FROM FULL GRANT IF IN + INDEX INFINITY INSERT INTO IS KEYSPACE LIMIT MATERIALIZED MODIFY NAN NORECURSIVE NOT NULL OF + ON OR ORDER PRIMARY RENAME REPLACE REVOKE SCHEMA SELECT SET TABLE TO TOKEN TRUNCATE UNLOGGED + UPDATE USE USING VIEW WHERE WITH`) { + reserved[w] = true + } +} + +// quoteName writes an identifier as CQL reads it back: bare when it is +// lowercase and not a reserved word, otherwise double-quoted. +func quoteName(name string) string { + bare := name != "" && name[0] >= 'a' && name[0] <= 'z' + for i := 0; bare && i < len(name); i++ { + c := name[i] + bare = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' + } + if bare && !reserved[strings.ToUpper(name)] { + return name + } + return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` +} + +func quoteStr(s string) string { + return "'" + strings.ReplaceAll(s, "'", "''") + "'" +} + +func asciiLower(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'A' && c <= 'Z' { + b[i] = c + 32 + } + } + return string(b) +} + +// cqlLiteral turns a cell's text into a CQL literal for a column of +// typeName (the type as system_schema writes it). Numbers, booleans, uuids, +// blobs and durations are bare, text and temporal values quoted; +// collections, tuples, vectors and UDTs are already CQL literals in cell +// text and stay as they are. nil is null. +func cqlLiteral(typeName string, value *string) string { + if value == nil { + return "null" + } + v := *value + t := asciiLower(strings.TrimSpace(typeName)) + for strings.HasPrefix(t, "frozen<") && strings.HasSuffix(t, ">") { + t = strings.TrimSpace(t[len("frozen<") : len(t)-1]) + } + trimmed := strings.TrimSpace(v) + ok := false + switch t { + case "tinyint", "smallint", "int", "bigint", "varint", "decimal", "float", "double", "counter": + ok = isNumber(trimmed) + case "boolean": + if b := asciiLower(trimmed); b == "true" || b == "false" { + return b + } + case "uuid", "timeuuid": + ok = isUUID(trimmed) + case "blob": + ok = isBlob(trimmed) + case "duration": + ok = trimmed != "" && strings.IndexFunc(trimmed, unicode.IsSpace) < 0 + case "text", "varchar", "ascii", "inet", "timestamp", "date", "time": + return quoteStr(v) + default: + // Collections, tuples, vectors and UDTs. + return v + } + if ok { + return trimmed + } + return quoteStr(v) +} + +func isDigits(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +func isNumber(v string) bool { + if v == "NaN" || v == "Infinity" || v == "-Infinity" { + return true + } + body := strings.TrimPrefix(v, "-") + if body == v { + body = strings.TrimPrefix(v, "+") + } + mantissa, exponent, hasExp := body, "", false + if i := strings.IndexAny(body, "eE"); i >= 0 { + mantissa, exponent, hasExp = body[:i], body[i+1:], true + } + digits := strings.Replace(mantissa, ".", "", 1) + if digits == "" || !isDigits(digits) || strings.Count(mantissa, ".") > 1 { + return false + } + if hasExp { + e := strings.TrimPrefix(exponent, "-") + if e == exponent { + e = strings.TrimPrefix(exponent, "+") + } + return e != "" && isDigits(e) + } + return true +} + +func isUUID(v string) bool { + if len(v) != 36 { + return false + } + for i := 0; i < len(v); i++ { + c := v[i] + if i == 8 || i == 13 || i == 18 || i == 23 { + if c != '-' { + return false + } + } else if !isHex(c) { + return false + } + } + return true +} + +func isHex(c byte) bool { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') +} + +func isBlob(v string) bool { + h, ok := strings.CutPrefix(v, "0x") + if !ok || len(h)%2 != 0 { + return false + } + for i := 0; i < len(h); i++ { + if !isHex(h[i]) { + return false + } + } + return true +} diff --git a/internal/drivers/mysql/edit.go b/internal/drivers/mysql/edit.go new file mode 100644 index 0000000..0fb24b2 --- /dev/null +++ b/internal/drivers/mysql/edit.go @@ -0,0 +1,650 @@ +package mysql + +// Grid editing: the result column metadata names the schema, table and +// column behind each value (empty for expressions); the table type, column +// types and unique keys come from information_schema in one round trip and +// are cached per session. Changes run as prepared statements with text +// parameters, which the server converts to the column type. + +import ( + "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." + severalTabs = "Read-only: the result combines columns from several tables." + unknownTable = "Read-only: the table behind this result could not be read." + previewMsg = "This value is only a preview and cannot be saved." + // Savepoint that bounds grid edits inside the user's transaction. + savepoint = "lq_apply" +) + +// mayBeEditable says whether a statement's metadata can name a single +// source table: plain queries, not VALUES or set operations. +func mayBeEditable(sql string) bool { + return isSelectLike(sql) && firstKeyword(sql) != "VALUES" && !hasSetOperation(sql) +} + +func isWordByte(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '$' +} + +func isASCIISpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' +} + +// hasSetOperation says whether the statement combines queries (UNION, +// INTERSECT, EXCEPT): the column metadata does not say which query each +// row came from. +func hasSetOperation(sql string) bool { + b := sql + i := 0 + for i < len(b) { + c := b[i] + switch { + case c == '\'' || c == '"' || c == '`': + i++ + for i < len(b) && b[i] != c { + if b[i] == '\\' && c != '`' { + i++ + } + i++ + } + i++ + case c == '#': + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '-' && i+1 < len(b) && b[i+1] == '-' && (i+2 >= len(b) || isASCIISpace(b[i+2])): + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(b) && b[i+1] == '*': + i += 2 + for i < len(b) && !(b[i] == '*' && i+1 < len(b) && b[i+1] == '/') { + i++ + } + i += 2 + case isWordByte(c): + start := i + for i < len(b) && isWordByte(b[i]) { + i++ + } + word := b[start:i] + if strings.EqualFold(word, "UNION") || strings.EqualFold(word, "INTERSECT") || + strings.EqualFold(word, "EXCEPT") { + return true + } + default: + i++ + } + } + return false +} + +// origin is where a result column comes from, as the protocol reports it. +type origin struct { + schema string + // Table alias in the query (tells a self-join apart). + alias string + table string + column string +} + +// originOf is nil for expressions, aggregates and literals (no original +// table). +func originOf(c column) *origin { + if c.orgTable == "" || c.orgName == "" { + return nil + } + return &origin{schema: c.schema, alias: c.table, table: c.orgTable, column: c.orgName} +} + +// singleTable is the one (schema, table) every base column of the result +// comes from, or why there is none. +func singleTable(origins []*origin) (schema, table, reason string) { + var found *origin + for _, o := range origins { + if o == nil { + continue + } + if found == nil { + found = o + } else if found.schema != o.schema || found.table != o.table || found.alias != o.alias { + return "", "", severalTabs + } + } + // Derived and temporary result tables have no schema. + if found == nil || found.schema == "" { + return "", "", notATable + } + return found.schema, found.table, "" +} + +// tableInfo is the catalog data of one table. +type tableInfo struct { + // BASE TABLE, VIEW...; empty when the table was not found. + tableType string + columns []tableColumn + // Unique indexes (PRIMARY included) with their columns in key order; a + // nil part is an expression. + keys []tableKey +} + +type tableColumn struct { + name string + // COLUMN_TYPE, as in DDL: int unsigned, varbinary(16), bit(5). + columnType string + nullable bool + generated bool +} + +type tableKey struct { + name string + parts []*string +} + +func cellText(row []*string, i int) string { + if i < len(row) && row[i] != nil { + return *row[i] + } + return "" +} + +// tableInfoFrom reads the three result sets of catalogSQL. +func tableInfoFrom(tables, columns, keys [][]*string) *tableInfo { + info := &tableInfo{} + if len(tables) > 0 { + info.tableType = cellText(tables[0], 0) + } + for _, r := range columns { + extra := strings.ToUpper(cellText(r, 3)) + generated := false + for _, g := range []string{"VIRTUAL GENERATED", "STORED GENERATED", "PERSISTENT GENERATED"} { + if strings.Contains(extra, g) { + generated = true + } + } + info.columns = append(info.columns, tableColumn{ + name: cellText(r, 0), + columnType: cellText(r, 1), + nullable: cellText(r, 2) == "YES", + generated: generated, + }) + } + for _, r := range keys { + name := cellText(r, 0) + var part *string + if len(r) > 1 && r[1] != nil { + p := *r[1] + part = &p + } + if n := len(info.keys); n > 0 && info.keys[n-1].name == name { + info.keys[n-1].parts = append(info.keys[n-1].parts, part) + } else { + info.keys = append(info.keys, tableKey{name: name, parts: []*string{part}}) + } + } + return info +} + +func (t *tableInfo) column(name string) *tableColumn { + for i := range t.columns { + if sameColumn(t.columns[i].name, name) { + return &t.columns[i] + } + } + return nil +} + +// sameColumn: column names are case-insensitive in MySQL and MariaDB. +func sameColumn(a, b string) bool { + return a == b || strings.ToLower(a) == strings.ToLower(b) +} + +// catalogSQL is three statements in one round trip: table type, columns, +// unique keys. +func catalogSQL(schema, table string) string { + filter := "TABLE_SCHEMA = " + stringLiteral(schema) + " AND TABLE_NAME = " + stringLiteral(table) + return "SELECT TABLE_TYPE FROM information_schema.TABLES WHERE " + filter + ";\n" + + "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, EXTRA FROM information_schema.COLUMNS " + + "WHERE " + filter + " ORDER BY ORDINAL_POSITION;\n" + + "SELECT INDEX_NAME, COLUMN_NAME FROM information_schema.STATISTICS " + + "WHERE " + filter + " AND NON_UNIQUE = 0 ORDER BY INDEX_NAME, SEQ_IN_INDEX" +} + +// editTarget is the edit target once the source table is known: its +// primary key (or, without one, a unique key on NOT NULL columns) must be in +// the result. Without a target, the reason says why. +func editTarget(schema, table string, info *tableInfo, origins []*origin) (*model.EditTarget, string) { + // SYSTEM VERSIONED: MariaDB tables that keep row history. + if info.tableType != "BASE TABLE" && info.tableType != "SYSTEM VERSIONED" { + return nil, notATable + } + var primary *tableKey + for i := range info.keys { + if info.keys[i].name == "PRIMARY" { + primary = &info.keys[i] + break + } + } + var candidates [][]*string + if primary != nil { + candidates = [][]*string{primary.parts} + } else { + keys: + for _, k := range info.keys { + for _, p := range k.parts { + if p == nil { + continue keys + } + if c := info.column(*p); c == nil || c.nullable { + continue keys + } + } + candidates = append(candidates, k.parts) + } + } + if len(candidates) == 0 { + return nil, "Read-only: table " + table + " has no primary key." + } + position := func(name string) int { + for i, o := range origins { + if o != nil && sameColumn(o.column, name) { + return i + } + } + return -1 + } + var key []int +candidates: + for _, parts := range candidates { + positions := make([]int, 0, len(parts)) + for _, p := range parts { + if p == nil { + continue candidates + } + i := position(*p) + if i < 0 { + continue candidates + } + positions = append(positions, i) + } + key = positions + break + } + if key == nil { + var names []string + for _, p := range candidates[0] { + if p != nil { + names = append(names, *p) + } + } + what := "key" + if primary != nil { + what = "primary key" + } + return nil, "Read-only: add the " + what + " columns (" + strings.Join(names, ", ") + + ") to the query to edit rows." + } + columns := make([]*model.EditColumn, len(origins)) + for i, o := range origins { + if o == nil { + continue + } + c := info.column(o.column) + if c == nil { + continue + } + // Generated columns cannot be written; key columns still need their + // name for the WHERE clause. + if c.generated && !containsInt(key, i) { + continue + } + columns[i] = &model.EditColumn{Name: c.name, TypeName: c.columnType} + } + s := schema + return &model.EditTarget{Schema: &s, Table: table, Columns: columns, Key: key}, "" +} + +func containsInt(list []int, v int) bool { + for _, x := range list { + if x == v { + return true + } + } + return false +} + +// conversion is how a grid value is sent for a column type (COLUMN_TYPE). +type conversion int + +const ( + // Text parameter; the server converts it to the column type. + convText conversion = iota + // TINYINT(1)/BOOLEAN: also accepts true and false. + convBool + // Binary strings and geometry, shown as 0x...: sent as hex to UNHEX(). + convHex + // BIT, shown as a number: sent as an integer. + convBit + // VECTOR, shown as [1.5,-2]. + convVector +) + +func conversionOf(columnType string) conversion { + t := strings.ToLower(strings.TrimSpace(columnType)) + base := t + if i := strings.IndexAny(t, "( "); i >= 0 { + base = t[:i] + } + switch base { + case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob", "geometry", "point", + "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", + "geometrycollection", "geomcollection": + return convHex + case "bit": + return convBit + case "vector": + return convVector + case "bool", "boolean": + return convBool + case "tinyint": + if strings.HasPrefix(t, "tinyint(1)") { + return convBool + } + } + return convText +} + +// placeholder is the SQL for one bound value of the given conversion. +func placeholder(conv conversion, engine model.Engine) string { + switch { + case conv == convHex: + return "UNHEX(?)" + case conv == convVector && engine == model.MariaDB: + return "VEC_FromText(?)" + case conv == convVector: + return "STRING_TO_VECTOR(?)" + } + return "?" +} + +func isHexDigit(c byte) bool { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') +} + +// bindValue is the parameter for a grid value shown by formatBytes. +func bindValue(conv conversion, text string) (param, error) { + switch conv { + case convBool: + t := strings.TrimSpace(text) + switch { + case strings.EqualFold(t, "true"): + return textParam("1"), nil + case strings.EqualFold(t, "false"): + return textParam("0"), nil + } + return textParam(text), nil + case convHex: + if strings.Contains(text, "… (") { + return param{}, apperr.New(apperr.Invalid, previewMsg) + } + t := strings.TrimSpace(text) + digits := t + if strings.HasPrefix(t, "0x") || strings.HasPrefix(t, "0X") { + digits = t[2:] + } + valid := len(digits)%2 == 0 + for i := 0; valid && i < len(digits); i++ { + valid = isHexDigit(digits[i]) + } + if !valid { + return param{}, apperr.New(apperr.Invalid, "Binary values are written in hexadecimal, like 0x00FF.") + } + return textParam(digits), nil + case convBit: + n, ok := parseBit(text) + if !ok { + return param{}, apperr.New(apperr.Invalid, + "BIT values are written as a number, like 5, or as 0x05 or b'101'.") + } + return uintParam(n), nil + } + return textParam(text), nil +} + +// parseUint parses like Rust's from_str_radix: an optional leading +. +func parseUint(s string, base int) (uint64, bool) { + if len(s) > 1 && s[0] == '+' { + s = s[1:] + } + if s == "" || s[0] == '+' || s[0] == '-' || strings.Contains(s, "_") { + return 0, false + } + n, err := strconv.ParseUint(s, base, 64) + return n, err == nil +} + +// parseBit reads 21, 0x15 or b'10101'. +func parseBit(text string) (uint64, bool) { + t := strings.TrimSpace(text) + if strings.HasPrefix(t, "0x") || strings.HasPrefix(t, "0X") { + h := t[2:] + if h == "" || len(h) > 16 { + return 0, false + } + return parseUint(h, 16) + } + if (strings.HasPrefix(t, "b'") || strings.HasPrefix(t, "B'")) && len(t) >= 3 && strings.HasSuffix(t, "'") { + bits := t[2 : len(t)-1] + if bits == "" || len(bits) > 64 { + return 0, false + } + return parseUint(bits, 2) + } + return parseUint(t, 10) +} + +// quoteIdent is a backtick-quoted identifier. +func quoteIdent(name string) string { + return "`" + strings.ReplaceAll(name, "`", "``") + "`" +} + +func tableRef(target *model.EditTarget) string { + if target.Schema != nil && *target.Schema != "" { + return quoteIdent(*target.Schema) + "." + quoteIdent(target.Table) + } + return quoteIdent(target.Table) +} + +func editColumn(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("Column %d of the result cannot be edited.", index+1) +} + +// statement is one prepared statement for a grid change. +type statement struct { + sql string + params []param +} + +type assignment struct { + col *model.EditColumn + value *string +} + +// assignments are the values per table column; a column given twice keeps +// the last value. +func assignments(target *model.EditTarget, values []model.CellValue) ([]assignment, error) { + var out []assignment + for _, v := range values { + col, err := editColumn(target, v.Column) + if err != nil { + return nil, err + } + found := false + for i := range out { + if sameColumn(out[i].col.Name, col.Name) { + out[i].value = v.Value + found = true + break + } + } + if !found { + out = append(out, assignment{col: col, value: v.Value}) + } + } + return out, nil +} + +// bound appends the parameter of one value and returns its placeholder. +func bound(col *model.EditColumn, v *string, engine model.Engine, params *[]param) (string, error) { + conv := conversionOf(col.TypeName) + if v == nil { + *params = append(*params, param{}) + } else { + p, err := bindValue(conv, *v) + if err != nil { + return "", err + } + *params = append(*params, p) + } + return placeholder(conv, engine), nil +} + +// pushWhere appends " WHERE k1 = ? AND k2 IS NULL", with the key values in +// params. +func pushWhere(sb *strings.Builder, params *[]param, target *model.EditTarget, engine model.Engine, + key []*string) error { + if len(key) != len(target.Key) { + return apperr.New(apperr.Invalid, "The row key does not match the result's key columns.") + } + for n, index := range target.Key { + col, err := editColumn(target, index) + if err != nil { + return err + } + if n == 0 { + sb.WriteString(" WHERE ") + } else { + sb.WriteString(" AND ") + } + sb.WriteString(quoteIdent(col.Name)) + if key[n] == nil { + sb.WriteString(" IS NULL") + continue + } + conv := conversionOf(col.TypeName) + p, err := bindValue(conv, *key[n]) + if err != nil { + return err + } + sb.WriteString(" = " + placeholder(conv, engine)) + *params = append(*params, p) + } + return nil +} + +// buildChange is the statement for one change; nil when an update changes +// nothing. +func buildChange(target *model.EditTarget, engine model.Engine, change model.RowChange) (*statement, error) { + table := tableRef(target) + var params []param + var sb strings.Builder + switch change.Op { + case model.OpUpdate: + set, err := assignments(target, change.Values) + if err != nil { + return nil, err + } + if len(set) == 0 { + return nil, nil + } + sb.WriteString("UPDATE " + table + " SET ") + for n, a := range set { + if n > 0 { + sb.WriteString(", ") + } + p, err := bound(a.col, a.value, engine, ¶ms) + if err != nil { + return nil, err + } + sb.WriteString(quoteIdent(a.col.Name) + " = " + p) + } + if err := pushWhere(&sb, ¶ms, target, engine, change.Key); err != nil { + return nil, err + } + case model.OpDelete: + sb.WriteString("DELETE FROM " + table) + if err := pushWhere(&sb, ¶ms, target, engine, change.Key); err != nil { + return nil, err + } + case model.OpInsert: + set, err := assignments(target, change.Values) + if err != nil { + return nil, err + } + if len(set) == 0 { + sb.WriteString("INSERT INTO " + table + " () VALUES ()") + break + } + names := make([]string, len(set)) + holders := make([]string, len(set)) + for i, a := range set { + names[i] = quoteIdent(a.col.Name) + if holders[i], err = bound(a.col, a.value, engine, ¶ms); err != nil { + return nil, err + } + } + sb.WriteString("INSERT INTO " + table + " (" + strings.Join(names, ", ") + ") VALUES (" + + strings.Join(holders, ", ") + ")") + default: + return nil, apperr.Invalidf("Unknown change %q.", change.Op) + } + return &statement{sql: sb.String(), params: params}, nil +} + +// atRow adds the 1-based row number to an error about one change. +func atRow(err error, index int) error { + e := *apperr.From(err) + if e.Detail == "" { + e.Detail = "Row " + strconv.Itoa(index+1) + " was not saved." + } + return &e +} + +// matchedRows is the rows an UPDATE matched, from the OK packet's info text +// ("Rows matched: 1 Changed: 0 Warnings: 0"; translated servers keep the +// order). Affected rows count only changed rows. +func matchedRows(info string) (uint64, bool) { + start := strings.IndexFunc(info, func(r rune) bool { return r >= '0' && r <= '9' }) + if start < 0 { + return 0, false + } + end := start + for end < len(info) && info[end] >= '0' && info[end] <= '9' { + end++ + } + n, err := strconv.ParseUint(info[start:end], 10, 64) + return n, err == nil +} + +func checkMatched(index int, matched uint64) error { + row := strconv.Itoa(index + 1) + switch matched { + case 1: + return nil + case 0: + return apperr.New(apperr.Database, + "Row "+row+" was not saved: 0 rows matched its key (changed or removed by someone else).") + } + return apperr.New(apperr.Database, "Row "+row+" was not saved: "+strconv.FormatUint(matched, 10)+ + " rows matched its key, which must match one.") +} diff --git a/internal/drivers/mysql/edit_test.go b/internal/drivers/mysql/edit_test.go new file mode 100644 index 0000000..ce93778 --- /dev/null +++ b/internal/drivers/mysql/edit_test.go @@ -0,0 +1,305 @@ +package mysql + +import ( + "reflect" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func o(alias, table, column string) *origin { + return &origin{schema: "db", alias: alias, table: table, column: column} +} + +func sp(s string) *string { return &s } + +// keyRows builds STATISTICS rows (index, column); an empty column is an +// expression key part (NULL). +func keyRows(keys ...[2]string) [][]*string { + out := make([][]*string, len(keys)) + for i, k := range keys { + out[i] = []*string{sp(k[0]), nil} + if k[1] != "" { + out[i][1] = sp(k[1]) + } + } + return out +} + +func testInfo(keys ...[2]string) *tableInfo { + return tableInfoFrom( + [][]*string{{sp("BASE TABLE")}}, + [][]*string{ + {sp("id"), sp("int"), sp("NO"), sp("auto_increment")}, + {sp("code"), sp("varchar(10)"), sp("NO"), sp("")}, + {sp("Name"), sp("varchar(20)"), sp("YES"), sp("")}, + {sp("up"), sp("varchar(20)"), sp("YES"), sp("VIRTUAL GENERATED")}, + }, + keyRows(keys...), + ) +} + +func TestFindsTheSingleSourceTable(t *testing.T) { + if s, tb, r := singleTable([]*origin{o("t", "t", "id"), nil, o("t", "t", "name")}); s != "db" || tb != "t" || r != "" { + t.Errorf("single: %q %q %q", s, tb, r) + } + if _, _, r := singleTable([]*origin{o("a", "t", "id"), o("b", "t", "id")}); r != severalTabs { + t.Errorf("self-join: %q", r) + } + if _, _, r := singleTable([]*origin{o("t", "t", "id"), o("u", "u", "id")}); r != severalTabs { + t.Errorf("join: %q", r) + } + if _, _, r := singleTable([]*origin{nil, nil}); r != notATable { + t.Errorf("expressions: %q", r) + } + derived := o("x", "x", "id") + derived.schema = "" + if _, _, r := singleTable([]*origin{derived}); r != notATable { + t.Errorf("derived: %q", r) + } +} + +func TestBuildsEditTargets(t *testing.T) { + pk := testInfo([2]string{"PRIMARY", "id"}) + origins := []*origin{o("t", "t", "name"), nil, o("t", "t", "ID"), o("t", "t", "up")} + target, reason := editTarget("db", "t", pk, origins) + if target == nil { + t.Fatal(reason) + } + if !reflect.DeepEqual(target.Key, []int{2}) || *target.Schema != "db" { + t.Errorf("key %v schema %s", target.Key, *target.Schema) + } + if c := target.Columns[0]; c == nil || c.Name != "Name" || c.TypeName != "varchar(20)" { + t.Errorf("column 0: %+v", c) + } + if target.Columns[1] != nil || target.Columns[2].Name != "id" { + t.Errorf("columns 1, 2: %+v %+v", target.Columns[1], target.Columns[2]) + } + // Generated columns stay read-only. + if target.Columns[3] != nil { + t.Error("generated column is editable") + } + + if _, r := editTarget("db", "t", pk, []*origin{o("t", "t", "code")}); r != + "Read-only: add the primary key columns (id) to the query to edit rows." { + t.Errorf("missing key: %q", r) + } + if _, r := editTarget("db", "t", testInfo(), origins); r != "Read-only: table t has no primary key." { + t.Errorf("no key: %q", r) + } + + // Without a primary key: unique keys on NOT NULL columns only. + unique := testInfo([2]string{"a_name", "Name"}, [2]string{"b_code", "code"}, [2]string{"b_code", "id"}) + target, reason = editTarget("db", "t", unique, + []*origin{o("t", "t", "id"), o("t", "t", "Name"), o("t", "t", "code")}) + if target == nil || !reflect.DeepEqual(target.Key, []int{2, 0}) { + t.Errorf("unique key: %+v %q", target, reason) + } + if _, r := editTarget("db", "t", unique, []*origin{o("t", "t", "id")}); r != + "Read-only: add the key columns (code, id) to the query to edit rows." { + t.Errorf("missing unique key: %q", r) + } + nullable := testInfo([2]string{"a_name", "Name"}) + if _, r := editTarget("db", "t", nullable, origins); r != "Read-only: table t has no primary key." { + t.Errorf("nullable key: %q", r) + } + // Expression key parts are unusable. + functional := testInfo([2]string{"f", ""}) + if functional.keys[0].parts[0] != nil { + t.Fatal("expression part read as a column") + } + if target, _ := editTarget("db", "t", functional, origins); target != nil { + t.Error("functional key accepted") + } + + view := testInfo([2]string{"PRIMARY", "id"}) + view.tableType = "VIEW" + if _, r := editTarget("db", "t", view, origins); r != notATable { + t.Errorf("view: %q", r) + } + if _, r := editTarget("db", "t", &tableInfo{}, origins); r != notATable { + t.Errorf("missing table: %q", r) + } +} + +func kindOf(err error) apperr.Kind { + if err == nil { + return "" + } + return apperr.From(err).Kind +} + +func TestConvertsValues(t *testing.T) { + for typ, want := range map[string]conversion{ + "varbinary(16)": convHex, + "LONGBLOB": convHex, + "point": convHex, + "bit(5)": convBit, + "tinyint(1)": convBool, + "tinyint(1) unsigned": convBool, + "tinyint(4)": convText, + "bigint unsigned": convText, + "json": convText, + "vector(3)": convVector, + "blob_like_name": convText, + } { + if got := conversionOf(typ); got != want { + t.Errorf("conversionOf(%q) = %d, want %d", typ, got, want) + } + } + + text := func(conv conversion, v string) string { + t.Helper() + p, err := bindValue(conv, v) + if err != nil || p.kind != paramText { + t.Fatalf("bindValue(%q): %v %v", v, p, err) + } + return p.text + } + if got := text(convHex, "0x00FF10"); got != "00FF10" { + t.Errorf("hex: %q", got) + } + if got := text(convHex, "cafe"); got != "cafe" { + t.Errorf("hex without prefix: %q", got) + } + if got := text(convHex, "0x"); got != "" { + t.Errorf("empty hex: %q", got) + } + for _, bad := range []string{"0x0", "0xZZ"} { + if _, err := bindValue(convHex, bad); kindOf(err) != apperr.Invalid { + t.Errorf("%q: %v", bad, err) + } + } + preview := formatBytes(typeBlob, binaryCharset, make([]byte, binaryPreviewBytes+1), binaryPreviewBytes) + if _, err := bindValue(convHex, preview); kindOf(err) != apperr.Invalid || apperr.From(err).Message != previewMsg { + t.Errorf("preview: %v", err) + } + for in, want := range map[string]uint64{ + "21": 21, "0x15": 21, "b'10101'": 21, "18446744073709551615": math64, + } { + p, err := bindValue(convBit, in) + if err != nil || p.kind != paramUint || p.num != want { + t.Errorf("bit %q: %v %v", in, p, err) + } + } + if _, err := bindValue(convBit, "x"); err == nil { + t.Error("bit x accepted") + } + for in, want := range map[string]string{"TRUE": "1", "false": "0", "1": "1"} { + if got := text(convBool, in); got != want { + t.Errorf("bool %q: %q", in, got) + } + } + raw := "it's \"x\"\n\\ … (3 bytes)" + if got := text(convText, raw); got != raw { + t.Errorf("text: %q", got) + } + for _, c := range []struct { + conv conversion + engine model.Engine + want string + }{ + {convHex, model.MySQL, "UNHEX(?)"}, + {convVector, model.MySQL, "STRING_TO_VECTOR(?)"}, + {convVector, model.MariaDB, "VEC_FromText(?)"}, + {convText, model.MySQL, "?"}, + } { + if got := placeholder(c.conv, c.engine); got != c.want { + t.Errorf("placeholder(%d, %s) = %q", c.conv, c.engine, got) + } + } +} + +const math64 = 18446744073709551615 + +func testTarget() *model.EditTarget { + col := func(name, typ string) *model.EditColumn { return &model.EditColumn{Name: name, TypeName: typ} } + return &model.EditTarget{ + Schema: sp("my db"), + Table: "Order`s", + Columns: []*model.EditColumn{ + col("Order Id", "int"), + col("data", "blob"), + nil, + col("flags", "bit(3)"), + col("k2", "varchar(5)"), + }, + Key: []int{0, 4}, + } +} + +func cv(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func TestBuildsChangeStatements(t *testing.T) { + target := testTarget() + key := []*string{sp("7"), nil} + check := func(change model.RowChange, sql string, params ...param) { + t.Helper() + s, err := buildChange(target, model.MySQL, change) + if err != nil { + t.Fatal(err) + } + if s == nil || s.sql != sql { + t.Fatalf("sql:\n got %+v\nwant %s", s, sql) + } + if len(s.params) != len(params) || (len(params) > 0 && !reflect.DeepEqual(s.params, params)) { + t.Errorf("params: got %v, want %v", s.params, params) + } + } + check(model.RowChange{Op: model.OpUpdate, Key: key, + Values: []model.CellValue{cv(1, sp("0xCAFE")), cv(3, sp("5")), cv(1, nil)}}, + "UPDATE `my db`.`Order``s` SET `data` = UNHEX(?), `flags` = ? WHERE `Order Id` = ? AND `k2` IS NULL", + param{}, uintParam(5), textParam("7")) + check(model.RowChange{Op: model.OpDelete, Key: key}, + "DELETE FROM `my db`.`Order``s` WHERE `Order Id` = ? AND `k2` IS NULL", textParam("7")) + check(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cv(4, sp("a'b")), cv(1, sp("0x00"))}}, + "INSERT INTO `my db`.`Order``s` (`k2`, `data`) VALUES (?, UNHEX(?))", textParam("a'b"), textParam("00")) + check(model.RowChange{Op: model.OpInsert}, "INSERT INTO `my db`.`Order``s` () VALUES ()") + + if s, err := buildChange(target, model.MySQL, model.RowChange{Op: model.OpUpdate, Key: key}); s != nil || err != nil { + t.Errorf("empty update: %+v %v", s, err) + } + + // Expression columns and malformed keys are rejected. + for _, bad := range []model.RowChange{ + {Op: model.OpUpdate, Key: key, Values: []model.CellValue{cv(2, sp("x"))}}, + {Op: model.OpDelete, Key: []*string{sp("7")}}, + {Op: model.OpInsert, Values: []model.CellValue{cv(9, sp("x"))}}, + {Op: "merge"}, + } { + if _, err := buildChange(target, model.MySQL, bad); kindOf(err) != apperr.Invalid { + t.Errorf("%+v: %v", bad, err) + } + } + // The row number goes in the detail. + e := apperr.From(atRow(apperr.New(apperr.Invalid, "x"), 2)) + if e.Detail != "Row 3 was not saved." { + t.Errorf("detail %q", e.Detail) + } +} + +func TestReadsMatchedRows(t *testing.T) { + if n, ok := matchedRows("Rows matched: 1 Changed: 0 Warnings: 0"); !ok || n != 1 { + t.Errorf("matched 1: %d %v", n, ok) + } + if n, ok := matchedRows("Rows matched: 0 Changed: 0 Warnings: 0"); !ok || n != 0 { + t.Errorf("matched 0: %d %v", n, ok) + } + if _, ok := matchedRows(""); ok { + t.Error("empty info") + } + if checkMatched(0, 1) != nil { + t.Error("one row") + } + e := apperr.From(checkMatched(2, 0)) + 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("no row: %+v", e) + } + if checkMatched(0, 2) == nil { + t.Error("two rows") + } +} diff --git a/internal/drivers/mysql/fake_test.go b/internal/drivers/mysql/fake_test.go new file mode 100644 index 0000000..6211c58 --- /dev/null +++ b/internal/drivers/mysql/fake_test.go @@ -0,0 +1,355 @@ +package mysql + +// A scripted MySQL server for tests without a real one. It speaks enough of +// the protocol for go-sql-driver's handshake (mysql_native_password, no TLS) +// and answers commands through a handler, recording each one. + +import ( + "bufio" + "encoding/binary" + "io" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +const ( + nullValue = "\x00NULL" + fakeConnID = 7 +) + +type fakeCol struct { + schema, table, orgTable, name, orgName string + typ byte + charset uint16 + flags uint16 +} + +// expr is a result column without a source table. +func expr(name string, typ byte) fakeCol { + return fakeCol{name: name, typ: typ, charset: 33} +} + +// tcol is a column of table app.t. +func tcol(alias, column string, typ byte) fakeCol { + return fakeCol{schema: "app", table: "t", orgTable: "t", name: alias, orgName: column, typ: typ, charset: 33} +} + +type fakeServer struct { + t *testing.T + ln net.Listener + deprecateEOF bool + // MariaDB: no CLIENT_MYSQL flag, extended capabilities with the + // metadata cache, and a metadata_follows byte in result headers. + mariadb atomic.Bool + authError atomic.Bool + handle func(c *fakeConn, sql string) + + mu sync.Mutex + commands []string + killed chan struct{} + quit chan struct{} +} + +func newFakeServer(t *testing.T, deprecateEOF bool, handle func(c *fakeConn, sql string)) *fakeServer { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := &fakeServer{t: t, ln: ln, deprecateEOF: deprecateEOF, handle: handle, + killed: make(chan struct{}, 4), quit: make(chan struct{}, 4)} + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go s.serve(conn) + } + }() + return s +} + +func (s *fakeServer) port() uint16 { + return uint16(s.ln.Addr().(*net.TCPAddr).Port) +} + +func (s *fakeServer) record(cmd string) { + s.mu.Lock() + s.commands = append(s.commands, cmd) + s.mu.Unlock() +} + +// take returns the commands received since the last call. +func (s *fakeServer) take() []string { + s.mu.Lock() + defer s.mu.Unlock() + out := s.commands + s.commands = nil + return out +} + +type fakeConn struct { + s *fakeServer + nc net.Conn + r *bufio.Reader + seq byte + status uint16 + // SQL of each prepared statement, by id. + stmts map[uint32]string +} + +func (c *fakeConn) read() ([]byte, error) { + var hdr [4]byte + if _, err := io.ReadFull(c.r, hdr[:]); err != nil { + return nil, err + } + n := int(hdr[0]) | int(hdr[1])<<8 | int(hdr[2])<<16 + c.seq = hdr[3] + 1 + data := make([]byte, n) + _, err := io.ReadFull(c.r, data) + return data, err +} + +func (c *fakeConn) send(payload []byte) { + n := len(payload) + out := append([]byte{byte(n), byte(n >> 8), byte(n >> 16), c.seq}, payload...) + c.seq++ + _, _ = c.nc.Write(out) +} + +func lenencStr(b []byte, s string) []byte { + b = appendLenenc(b, uint64(len(s))) + return append(b, s...) +} + +func (c *fakeConn) ok(affected uint64, info string, more bool) { + status := c.status + if more { + status |= statusMoreResults + } + p := []byte{pktOK} + p = appendLenenc(p, affected) + p = appendLenenc(p, 0) + p = binary.LittleEndian.AppendUint16(p, status) + p = binary.LittleEndian.AppendUint16(p, 0) + c.send(append(p, info...)) +} + +func (c *fakeConn) fail(code uint16, state, message string) { + p := []byte{pktERR} + p = binary.LittleEndian.AppendUint16(p, code) + p = append(p, '#') + p = append(p, state...) + c.send(append(p, message...)) +} + +func (c *fakeConn) columns(cols []fakeCol) { + header := appendLenenc(nil, uint64(len(cols))) + if c.s.mariadb.Load() { + header = append(header, 1) // metadata follows + } + c.send(header) + c.definitions(cols) +} + +// definitions sends column definitions, then EOF when the client still +// expects one. +func (c *fakeConn) definitions(cols []fakeCol) { + for _, col := range cols { + p := lenencStr(nil, "def") + for _, s := range []string{col.schema, col.table, col.orgTable, col.name, col.orgName} { + p = lenencStr(p, s) + } + p = append(p, 0x0c) + p = binary.LittleEndian.AppendUint16(p, col.charset) + p = binary.LittleEndian.AppendUint32(p, 255) + p = append(p, col.typ) + p = binary.LittleEndian.AppendUint16(p, col.flags) + p = append(p, 0, 0, 0) + c.send(p) + } + if !c.s.deprecateEOF { + c.eof(0, false) + } +} + +func (c *fakeConn) eof(warnings uint16, more bool) { + status := c.status + if more { + status |= statusMoreResults + } + if c.s.deprecateEOF { + p := []byte{pktEOF, 0, 0} + p = binary.LittleEndian.AppendUint16(p, status) + c.send(binary.LittleEndian.AppendUint16(p, warnings)) + return + } + p := []byte{pktEOF} + p = binary.LittleEndian.AppendUint16(p, warnings) + c.send(binary.LittleEndian.AppendUint16(p, status)) +} + +// result sends a text result set; nullValue is NULL. +func (c *fakeConn) result(cols []fakeCol, rows [][]string, warnings uint16, more bool) { + c.columns(cols) + for _, r := range rows { + var p []byte + for _, v := range r { + if v == nullValue { + p = append(p, 0xfb) + } else { + p = lenencStr(p, v) + } + } + c.send(p) + } + c.eof(warnings, more) +} + +func (s *fakeServer) serve(nc net.Conn) { + defer func() { _ = nc.Close() }() + c := &fakeConn{s: s, nc: nc, r: bufio.NewReader(nc), status: statusAutocommit, stmts: map[uint32]string{}} + caps := uint32(4 | 8 | 0x200 | 0x2000 | 0x8000 | 0x10000 | 0x20000 | 0x40000 | 0x80000 | 0x100000 | 0x200000) + if s.deprecateEOF { + caps |= capDeprecateEOF + } + g := []byte{10} + g = append(g, "8.4.2-fake\x00"...) + g = binary.LittleEndian.AppendUint32(g, fakeConnID) + g = append(g, "abcdefgh"...) + g = append(g, 0) + g = binary.LittleEndian.AppendUint16(g, uint16(caps)) + g = append(g, 45) + g = binary.LittleEndian.AppendUint16(g, statusAutocommit) + g = binary.LittleEndian.AppendUint16(g, uint16(caps>>16)) + g = append(g, 21) + g = append(g, make([]byte, 6)...) + if s.mariadb.Load() { + g = binary.LittleEndian.AppendUint32(g, extCacheMetadata) + } else { + g = append(g, 0, 0, 0, 0) + } + g = append(g, "ijklmnopqrst\x00"...) + g = append(g, "mysql_native_password\x00"...) + c.seq = 0 + c.send(g) + if _, err := c.read(); err != nil { + return + } + if s.authError.Load() { + c.fail(1045, "28000", "Access denied for user 'x'@'localhost' (using password: YES)") + return + } + c.ok(0, "", false) + + for { + data, err := c.read() + if err != nil || len(data) == 0 { + return + } + switch data[0] { + case 0x01: + s.record("QUIT") + s.quit <- struct{}{} + return + case comQuery: + sql := string(data[1:]) + if strings.HasPrefix(sql, "KILL QUERY ") { + s.record(sql) + c.ok(0, "", false) + s.killed <- struct{}{} + continue + } + s.record(sql) + s.handle(c, sql) + case comStmtPrepare: + sql := string(data[1:]) + s.record("PREPARE " + sql) + id := uint32(len(c.stmts) + 1) + c.stmts[id] = sql + params := strings.Count(sql, "?") + p := []byte{pktOK} + p = binary.LittleEndian.AppendUint32(p, id) + p = binary.LittleEndian.AppendUint16(p, 0) + p = binary.LittleEndian.AppendUint16(p, uint16(params)) + c.send(append(p, 0, 0, 0)) + if params > 0 { + p := make([]fakeCol, params) + for i := range p { + p[i] = expr("?", typeVarString) + } + c.definitions(p) + } + case comStmtExecute: + id := binary.LittleEndian.Uint32(data[1:5]) + sql := c.stmts[id] + params := decodeParams(data[10:], strings.Count(sql, "?")) + s.record("EXECUTE " + strings.Join(params, ", ")) + s.handle(c, "EXECUTE "+sql+" ["+strings.Join(params, ", ")+"]") + case comStmtClose: + s.record("CLOSE " + strconv.Itoa(int(binary.LittleEndian.Uint32(data[1:5])))) + default: + c.fail(1047, "08S01", "Unknown command") + } + } +} + +// decodeParams reads the parameters of COM_STMT_EXECUTE as text: NULL, +// strings and unsigned integers. +func decodeParams(b []byte, n int) []string { + if n == 0 { + return nil + } + nulls := b[:(n+7)/8] + pos := len(nulls) + 1 + types := b[pos : pos+2*n] + pos += 2 * n + out := make([]string, n) + for i := range out { + switch { + case nulls[i/8]&(1<<(i%8)) != 0: + out[i] = "NULL" + case types[2*i] == typeLongLong: + out[i] = strconv.FormatUint(binary.LittleEndian.Uint64(b[pos:]), 10) + "u" + pos += 8 + default: + v, _, m := readLenencBytes(b[pos:]) + out[i] = strconv.Quote(string(v)) + pos += m + } + } + return out +} + +// countResult sends the binary result of SELECT COUNT(*). +func (c *fakeConn) countResult(n uint64) { + c.columns([]fakeCol{{name: "COUNT(*)", typ: typeLongLong, charset: 63}}) + p := []byte{0, 0} + c.send(binary.LittleEndian.AppendUint64(p, n)) + c.eof(0, false) +} + +// waitFor waits for a signal from the server. +func waitFor(t *testing.T, ch chan struct{}, what string) { + t.Helper() + if !signalled(ch) { + t.Fatalf("timed out waiting for %s", what) + } +} + +// signalled waits for a signal; usable from the server's goroutines. +func signalled(ch chan struct{}) bool { + select { + case <-ch: + return true + case <-time.After(10 * time.Second): + return false + } +} diff --git a/internal/drivers/mysql/integration_test.go b/internal/drivers/mysql/integration_test.go new file mode 100644 index 0000000..64be730 --- /dev/null +++ b/internal/drivers/mysql/integration_test.go @@ -0,0 +1,769 @@ +package mysql + +// Tests against a real server. They only run with LQ_MYSQL_HOST set (and +// optionally LQ_MYSQL_PORT, LQ_MYSQL_USER, LQ_MYSQL_PASSWORD, LQ_MYSQL_DB and +// LQ_MYSQL_ENGINE, "mysql" or "mariadb"). + +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 myProfile(t *testing.T) (model.ConnectionProfile, *string) { + t.Helper() + host := os.Getenv("LQ_MYSQL_HOST") + if host == "" { + t.Skip("LQ_MYSQL_HOST is not set") + } + p := model.DefaultProfile() + p.Name = "test" + p.Engine = model.MySQL + if os.Getenv("LQ_MYSQL_ENGINE") == "mariadb" { + p.Engine = model.MariaDB + } + p.Host = host + p.Port = 3306 + if port, err := strconv.ParseUint(os.Getenv("LQ_MYSQL_PORT"), 10, 16); err == nil { + p.Port = uint16(port) + } + p.User = env("LQ_MYSQL_USER", "root") + p.Database = env("LQ_MYSQL_DB", "lowquery") + p.SslMode = model.SslPrefer + var password *string + if pw := os.Getenv("LQ_MYSQL_PASSWORD"); pw != "" { + password = &pw + } + return p, password +} + +func mySession(t *testing.T) *Session { + t.Helper() + p, password := myProfile(t) + s, err := Connect(context.Background(), p, password) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func execMax(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 run(t *testing.T, s *Session, sql string) *model.ExecResult { + t.Helper() + return execMax(t, s, sql, 100) +} + +// texts shows rows with NULL as "NULL", for comparisons. +func texts(t *testing.T, s *Session, sql string) [][]string { + t.Helper() + rows := run(t, s, sql).Rows + out := make([][]string, len(rows)) + for i, r := range rows { + out[i] = cells(r) + } + return out +} + +func first(t *testing.T, s *Session, sql string) string { + t.Helper() + rows := texts(t, s, sql) + if len(rows) == 0 || len(rows[0]) == 0 { + t.Fatalf("%s: no rows", sql) + } + return rows[0][0] +} + +func editable(t *testing.T, s *Session, sql string) *model.EditTarget { + t.Helper() + r := run(t, s, sql) + if r.ReadOnlyReason != nil { + t.Fatalf("%s: %s", sql, *r.ReadOnlyReason) + } + if r.Editable == nil { + t.Fatalf("%s: not editable, no reason", sql) + } + return r.Editable +} + +func readOnly(t *testing.T, s *Session, sql string) string { + t.Helper() + r := run(t, s, sql) + if r.Editable != nil { + t.Fatalf("%s: editable", sql) + } + if r.ReadOnlyReason == nil { + t.Fatalf("%s: no reason", sql) + } + return *r.ReadOnlyReason +} + +func keyOf(values ...string) []*string { + out := make([]*string, len(values)) + for i, v := range values { + out[i] = sp(v) + } + return out +} + +func insertOf(values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpInsert, Values: values} +} + +func updateOf(key []*string, values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: key, Values: values} +} + +func deleteOf(key ...string) model.RowChange { + return model.RowChange{Op: model.OpDelete, Key: keyOf(key...)} +} + +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 TestMySQLConnectsAndReportsVersion(t *testing.T) { + s := mySession(t) + product := "MySQL " + if s.Engine() == model.MariaDB { + product = "MariaDB " + } + if !strings.HasPrefix(s.ServerVersion(), product) { + t.Errorf("version %q", s.ServerVersion()) + } + if s.CurrentUser() == nil { + t.Error("no current user") + } + p, _ := myProfile(t) + if s.CurrentSchema() == nil || *s.CurrentSchema() != p.Database { + t.Errorf("schema %v", strOrNil(s.CurrentSchema())) + } + if st := s.TxState(); !st.Autocommit || st.InTransaction { + t.Errorf("state %+v", st) + } + + p.SslMode = model.SslRequire + _, err := Connect(context.Background(), p, model.Str("wrong password")) + if e := apperr.From(err); e == nil || e.Kind != apperr.Connection || e.Code != "1045 (28000)" { + t.Errorf("wrong password: %+v", e) + } +} + +func TestMySQLFormatsValuesExactly(t *testing.T) { + s := mySession(t) + run(t, s, "SET SESSION sql_mode = ''") + run(t, s, `CREATE TEMPORARY TABLE lq_types (d DECIMAL(30,9), u BIGINT UNSIGNED, dt DATETIME(6), + j JSON, b BLOB, vb VARBINARY(4), n INT, bt BIT(5), e ENUM('x','y'), f DOUBLE, + z DATETIME, t VARCHAR(10))`) + r := run(t, s, `INSERT INTO lq_types VALUES (12345678901234567890.123456789, 18446744073709551615, + '2024-05-01 13:45:00.123456', '{"a": 1}', x'00FF10', x'CAFE', NULL, b'10101', 'y', + 1.5, '0000-00-00 00:00:00', 'ação')`) + if r.RowsAffected == nil || *r.RowsAffected != 1 { + t.Errorf("affected %v", r.RowsAffected) + } + r = run(t, s, "SELECT * FROM lq_types") + want := []string{"12345678901234567890.123456789", "18446744073709551615", "2024-05-01 13:45:00.123456", + `{"a": 1}`, "0x00FF10", "0xCAFE", "NULL", "21", "y", "1.5", "0000-00-00 00:00:00", "ação"} + if got := cells(r.Rows[0]); !reflect.DeepEqual(got, want) { + t.Errorf("row:\n got %q\nwant %q", got, want) + } + cols := r.Columns + if cols[0].Kind != model.KindNumber || cols[1].TypeName != "BIGINT UNSIGNED" || + cols[2].Kind != model.KindTemporal || cols[4].Kind != model.KindBinary || cols[11].Kind != model.KindText { + t.Errorf("columns: %+v", cols) + } + if s.Engine() == model.MySQL && cols[3].Kind != model.KindJSON { + t.Errorf("json kind %q", cols[3].Kind) + } +} + +func TestMySQLLimitsRowsOnTheServer(t *testing.T) { + s := mySession(t) + run(t, s, "CREATE TEMPORARY TABLE lq_limit (n INT)") + values := make([]string, 50) + for i := range values { + values[i] = "(" + strconv.Itoa(i+1) + ")" + } + run(t, s, "INSERT INTO lq_limit VALUES "+strings.Join(values, ",")) + + r := execMax(t, s, "SELECT n FROM lq_limit ORDER BY n", 10) + if len(r.Rows) != 10 || !r.Truncated { + t.Errorf("limit 10: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + r = execMax(t, s, "SELECT n FROM lq_limit", 50) + if len(r.Rows) != 50 || r.Truncated { + t.Errorf("limit 50: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + + // The limit does not leak into the next statements. + r = execMax(t, s, "UPDATE lq_limit SET n = n + 1", 10) + if r.RowsAffected == nil || *r.RowsAffected != 50 { + t.Errorf("update: %v", r.RowsAffected) + } + if r := execMax(t, s, "SELECT n FROM lq_limit", 0); len(r.Rows) != 50 { + t.Errorf("no limit: %d rows", len(r.Rows)) + } + if got := texts(t, s, "SHOW VARIABLES LIKE 'sql_select_limit'"); got[0][1] != "18446744073709551615" { + t.Errorf("sql_select_limit %q", got) + } +} + +func TestMySQLReportsErrorsWithPosition(t *testing.T) { + s := mySession(t) + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT *\nFROMM lq_x", MaxRows: 10}) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || e.Code != "1064 (42000)" || e.Position == nil || *e.Position != 9 { + t.Errorf("syntax error: %+v", e) + } + _, err = s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT * FROM lq_no_such_table", MaxRows: 10}) + if e := apperr.From(err); e == nil || e.Code != "1146 (42S02)" { + t.Errorf("missing table: %+v", e) + } + // The session still works. + if got := first(t, s, "SELECT 1"); got != "1" { + t.Errorf("after errors: %q", got) + } +} + +func TestMySQLCollectsWarnings(t *testing.T) { + s := mySession(t) + r := run(t, s, "SELECT CAST('abc' AS SIGNED)") + found := false + for _, n := range r.Notices { + found = found || strings.HasPrefix(n, "Warning 1292:") + } + if !found { + t.Errorf("notices %q", r.Notices) + } + if r := run(t, s, "SELECT 1"); len(r.Notices) != 0 { + t.Errorf("notices after SELECT 1: %q", r.Notices) + } +} + +func TestMySQLManualTransactions(t *testing.T) { + s := mySession(t) + ctx := context.Background() + run(t, s, "DROP TABLE IF EXISTS lq_tx") + run(t, s, "CREATE TABLE lq_tx (n INT) ENGINE = InnoDB") + + st, err := s.SetAutocommit(ctx, false) + if err != nil || st.Autocommit { + t.Fatalf("autocommit off: %+v %v", st, err) + } + if r := run(t, s, "INSERT INTO lq_tx VALUES (1)"); !r.InTransaction { + t.Error("insert outside a transaction") + } + if st, err := s.EndTransaction(ctx, false); err != nil || st.InTransaction { + t.Fatalf("rollback: %+v %v", st, err) + } + if got := first(t, s, "SELECT COUNT(*) FROM lq_tx"); got != "0" { + t.Errorf("after rollback: %s", got) + } + run(t, s, "INSERT INTO lq_tx VALUES (2)") + if st, err := s.EndTransaction(ctx, true); err != nil || st.InTransaction { + t.Fatalf("commit: %+v %v", st, err) + } + run(t, s, "INSERT INTO lq_tx VALUES (3)") + // Turning autocommit back on commits pending work. + if st, err := s.SetAutocommit(ctx, true); err != nil || !st.Autocommit || st.InTransaction { + t.Fatalf("autocommit on: %+v %v", st, err) + } + if got := first(t, s, "SELECT COUNT(*) FROM lq_tx"); got != "2" { + t.Errorf("after autocommit: %s", got) + } + + // Explicit transaction in autocommit mode. + if !run(t, s, "START TRANSACTION").InTransaction || !run(t, s, "DELETE FROM lq_tx").InTransaction || + run(t, s, "ROLLBACK").InTransaction { + t.Error("explicit transaction state") + } + if got := first(t, s, "SELECT COUNT(*) FROM lq_tx"); got != "2" { + t.Errorf("after explicit rollback: %s", got) + } + run(t, s, "DROP TABLE lq_tx") +} + +func checkCancelled(t *testing.T, s *Session, err error, started time.Time) { + t.Helper() + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Errorf("error %+v", e) + } + if time.Since(started) > 15*time.Second { + t.Error("cancel took too long") + } + if got := first(t, s, "SELECT 2"); got != "2" { + t.Errorf("after cancel: %q", got) + } +} + +func TestMySQLCancelsARunningQuery(t *testing.T) { + s := mySession(t) + started := time.Now() + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT SLEEP(30)", MaxRows: 10}) + done <- err + }() + time.Sleep(time.Second) + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + checkCancelled(t, s, err, started) + case <-time.After(20 * time.Second): + t.Fatal("the query was not cancelled") + } +} + +func TestMySQLContextCancelsQuery(t *testing.T) { + s := mySession(t) + started := time.Now() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _, err := s.Execute(ctx, model.ExecRequest{SQL: "SELECT SLEEP(30)", MaxRows: 10}) + checkCancelled(t, s, err, started) +} + +func TestMySQLStream(t *testing.T) { + s := mySession(t) + sink := make(chan drivers.StreamEvent, 10) + // MySQL stops recursive CTEs at 1000 rows by default: digits instead. + total, err := s.Stream(context.Background(), `WITH d (n) AS (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 + UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 + UNION ALL SELECT 8 UNION ALL SELECT 9) + SELECT n, CASE WHEN n = 1 THEN UNHEX(REPEAT('AB', 40000)) END + FROM (SELECT a.n + 10 * b.n + 100 * c.n + 1000 * e.n + 1 AS n FROM d a, d b, d c, d e) x + WHERE n <= 1234 ORDER BY n`, 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 _, err := s.Stream(context.Background(), "DO 1", make(chan drivers.StreamEvent, 1)); kindOf(err) != apperr.Invalid { + t.Errorf("statement without rows: %v", err) + } +} + +func isSystem(names []string) bool { + for _, n := range names { + if !isSystemSchema(n) { + return false + } + } + return true +} + +func TestMySQLListsMetadata(t *testing.T) { + s := mySession(t) + ctx := context.Background() + db := *s.CurrentSchema() + for _, sql := range []string{ + "DROP VIEW IF EXISTS lq_meta_v", + "DROP TABLE IF EXISTS lq_meta_t", + "DROP PROCEDURE IF EXISTS lq_meta_p", + "DROP FUNCTION IF EXISTS lq_meta_f", + "CREATE TABLE lq_meta_t (id INT NOT NULL PRIMARY KEY, name VARCHAR(20) NULL)", + "CREATE VIEW lq_meta_v AS SELECT id FROM lq_meta_t", + "CREATE PROCEDURE lq_meta_p() SELECT 1", + "CREATE FUNCTION lq_meta_f() RETURNS INT DETERMINISTIC RETURN 1", + } { + run(t, s, sql) + } + mariadb := s.Engine() == model.MariaDB + if mariadb { + run(t, s, "CREATE OR REPLACE SEQUENCE lq_meta_s") + } + + schemas, err := s.ListSchemas(ctx) + if err != nil || len(schemas) == 0 || schemas[0] != db { + t.Fatalf("schemas: %q %v", schemas, err) + } + firstSystem := -1 + for i, n := range schemas { + if isSystemSchema(n) { + firstSystem = i + break + } + } + if firstSystem < 0 || !isSystem(schemas[firstSystem:]) { + t.Errorf("system schemas not last: %q", schemas) + } + + objects, err := s.ListObjects(ctx, db) + if err != nil { + t.Fatal(err) + } + kind := func(name string) string { + for _, o := range objects { + if o.Name == name { + return o.Kind + } + } + return "" + } + for name, want := range map[string]string{ + "lq_meta_t": "table", "lq_meta_v": "view", "lq_meta_p": "procedure", "lq_meta_f": "function", + } { + if got := kind(name); got != want { + t.Errorf("%s: %q", name, got) + } + } + if mariadb && kind("lq_meta_s") != "sequence" { + t.Errorf("sequence: %q", kind("lq_meta_s")) + } + + cols, err := s.ListColumns(ctx, db, "lq_meta_t") + if err != nil || len(cols) != 2 { + t.Fatalf("columns: %+v %v", cols, err) + } + // MariaDB keeps the display width: int(11). + if cols[0].Name != "id" || !strings.HasPrefix(cols[0].TypeName, "int") || !cols[0].PrimaryKey || cols[0].Nullable { + t.Errorf("id: %+v", cols[0]) + } + if cols[1].TypeName != "varchar(20)" || cols[1].PrimaryKey || !cols[1].Nullable { + t.Errorf("name: %+v", cols[1]) + } + + // CALL: rows of the first result set plus the affected rows. + r := run(t, s, "CALL lq_meta_p()") + if len(r.Rows) == 0 || *r.Rows[0][0] != "1" || r.RowsAffected == nil { + t.Errorf("call: %+v", r) + } +} + +func TestMySQLDetectsEditableResults(t *testing.T) { + s := mySession(t) + db := *s.CurrentSchema() + for _, sql := range []string{ + "DROP VIEW IF EXISTS lq_edit_v", + "DROP TABLE IF EXISTS lq_edit_a, lq_edit_b, lq_edit_nokey, lq_edit_uk", + "CREATE TABLE lq_edit_a (id INT NOT NULL PRIMARY KEY, name VARCHAR(20), b_id INT)", + "CREATE TABLE lq_edit_b (id INT NOT NULL PRIMARY KEY, label VARCHAR(20))", + "CREATE TABLE lq_edit_nokey (n INT, m INT)", + "CREATE TABLE lq_edit_uk (a INT NOT NULL, b INT NOT NULL, c INT, UNIQUE KEY uk (b, a))", + "CREATE VIEW lq_edit_v AS SELECT id, name FROM lq_edit_a", + } { + run(t, s, sql) + } + + target := editable(t, s, "SELECT id, name, id * 2 AS dbl FROM lq_edit_a") + if *target.Schema != db || target.Table != "lq_edit_a" || !reflect.DeepEqual(target.Key, []int{0}) { + t.Errorf("target: %+v", target) + } + if c := target.Columns[1]; c == nil || c.Name != "name" || c.TypeName != "varchar(20)" || target.Columns[2] != nil { + t.Errorf("columns: %+v", target.Columns) + } + target = editable(t, s, "SELECT name AS n, x.id FROM lq_edit_a x WHERE 1 = 0") + if !reflect.DeepEqual(target.Key, []int{1}) || target.Columns[0].Name != "name" { + t.Errorf("alias: %+v", target) + } + if target := editable(t, s, "SELECT c, a, b FROM lq_edit_uk"); !reflect.DeepEqual(target.Key, []int{2, 1}) { + t.Errorf("unique key: %v", target.Key) + } + + for sql, want := range map[string]string{ + "SELECT a.id, b.label FROM lq_edit_a a JOIN lq_edit_b b ON b.id = a.b_id": severalTabs, + "SELECT a.id, b.id FROM lq_edit_a a JOIN lq_edit_a b ON a.id = b.id": severalTabs, + "SELECT * FROM lq_edit_nokey": "Read-only: table lq_edit_nokey has no primary key.", + "SELECT name FROM lq_edit_a": "Read-only: add the primary key columns (id) to the query to edit rows.", + "SELECT COUNT(*) FROM lq_edit_a": notATable, + "SELECT id FROM lq_edit_a UNION SELECT id FROM lq_edit_b": notATable, + } { + if got := readOnly(t, s, sql); got != want { + t.Errorf("%s: %q", sql, got) + } + } + readOnly(t, s, "SHOW TABLES") + // A view is read-only, unless the server names its base table. + r := run(t, s, "SELECT * FROM lq_edit_v") + if r.Editable != nil { + if r.Editable.Table != "lq_edit_a" { + t.Errorf("view target: %+v", r.Editable) + } + } else if strOrNil(r.ReadOnlyReason) != notATable { + t.Errorf("view: %s", strOrNil(r.ReadOnlyReason)) + } + if r := run(t, s, "UPDATE lq_edit_a SET name = name"); r.Editable != nil || r.ReadOnlyReason != nil { + t.Errorf("update: %+v", r) + } + + // DDL clears the cached catalog. + run(t, s, "ALTER TABLE lq_edit_nokey ADD PRIMARY KEY (n)") + if target := editable(t, s, "SELECT m, n FROM lq_edit_nokey"); !reflect.DeepEqual(target.Key, []int{1}) { + t.Errorf("after ALTER: %v", target.Key) + } + + run(t, s, "DROP VIEW lq_edit_v") + run(t, s, "DROP TABLE lq_edit_a, lq_edit_b, lq_edit_nokey, lq_edit_uk") +} + +func TestMySQLRoundTripsEveryType(t *testing.T) { + s := mySession(t) + run(t, s, "DROP TABLE IF EXISTS lq_edit_types") + run(t, s, `CREATE TABLE lq_edit_types (id INT AUTO_INCREMENT PRIMARY KEY, d DECIMAL(30,9), + i BIGINT, u BIGINT UNSIGNED, f DOUBLE, fl FLOAT, b BOOLEAN, dt DATE, + ts DATETIME(6), tz TIMESTAMP(3) NULL, tm TIME(6), y YEAR, txt TEXT, + vc VARCHAR(100), bin VARBINARY(16), bl BLOB, bt BIT(5), j JSON, + e ENUM('x','y'), n VARCHAR(5) NULL) DEFAULT CHARSET = utf8mb4`) + target := editable(t, s, "SELECT * FROM lq_edit_types") + if c := target.Columns[14]; c == nil || c.TypeName != "varbinary(16)" { + t.Errorf("bin column: %+v", c) + } + + expected := []*string{ + sp("12345678901234567890.123456789"), + sp("-9223372036854775808"), + sp("18446744073709551615"), + sp("-1234.5678"), + sp("1.5"), + sp("1"), + sp("2024-02-29"), + sp("2024-05-01 13:45:00.123456"), + sp("2024-05-01 13:45:00.120"), + sp("-12:34:56.789000"), + sp("2024"), + sp("it's \"quoted\"\nline 2 \\ back"), + sp("ação 😀"), + sp("0x00FF10CA"), + sp("0xDEADBEEF"), + sp("21"), + sp(`{"a": 1, "b": [true, null]}`), + sp("y"), + nil, + } + values := make([]model.CellValue, len(expected)) + for i, v := range expected { + values[i] = cv(i+1, v) + } + r, err := apply(s, target, insertOf(values...)) + if err != nil || r.Inserted != 1 || r.InTransaction { + t.Fatalf("insert: %+v %v", r, err) + } + + rows := run(t, s, "SELECT * FROM lq_edit_types").Rows + if got, want := cells(rows[0][1:]), cells(expected); !reflect.DeepEqual(got, want) { + t.Errorf("values:\n got %q\nwant %q", got, want) + } + + // Every column saved with its own displayed text stays identical + // (nothing changes, so the server reports 0 affected rows). + id := *rows[0][0] + same := make([]model.CellValue, 0, len(rows[0])-1) + for i := 1; i < len(rows[0]); i++ { + same = append(same, cv(i, rows[0][i])) + } + r, err = apply(s, target, updateOf(keyOf(id), same...)) + if err != nil || r.Updated != 1 { + t.Fatalf("same values: %+v %v", r, err) + } + before := make([][]string, len(rows)) + for i, row := range rows { + before[i] = cells(row) + } + if got := texts(t, s, "SELECT * FROM lq_edit_types"); !reflect.DeepEqual(got, before) { + t.Errorf("after saving the same values:\n got %q\nwant %q", got, before) + } + + // Changed values, committed for other sessions too. + r, err = apply(s, target, updateOf(keyOf(id), cv(15, sp("0x")), cv(16, sp("2")), cv(19, sp("ok")), cv(6, nil))) + if err != nil || r.Updated != 1 || r.InTransaction { + t.Fatalf("changes: %+v %v", r, err) + } + other := mySession(t) + if got := texts(t, other, "SELECT bl, bt, n, b FROM lq_edit_types"); !reflect.DeepEqual(got[0], + []string{"0x", "2", "ok", "NULL"}) { + t.Errorf("seen from another session: %q", got) + } + + r, err = apply(s, target, insertOf(), deleteOf(id)) + if err != nil || r.Inserted != 1 || r.Deleted != 1 { + t.Fatalf("insert and delete: %+v %v", r, err) + } + got := texts(t, other, "SELECT id, e, n FROM lq_edit_types") + if len(got) != 1 || got[0][0] == id { + t.Errorf("rows: %q", got) + } + run(t, s, "DROP TABLE lq_edit_types") +} + +func TestMySQLFailedChangesRollBack(t *testing.T) { + s := mySession(t) + run(t, s, "DROP TABLE IF EXISTS lq_edit_rb") + run(t, s, "CREATE TABLE lq_edit_rb (id INT PRIMARY KEY, v VARCHAR(10), bl BLOB) ENGINE = InnoDB") + run(t, s, "INSERT INTO lq_edit_rb VALUES (1, 'a', NULL), (2, 'b', NULL)") + target := editable(t, s, "SELECT id, v, bl FROM lq_edit_rb") + before := texts(t, s, "SELECT * FROM lq_edit_rb ORDER BY id") + + _, err := apply(s, target, + updateOf(keyOf("1"), cv(1, sp("changed"))), + deleteOf("2"), + updateOf(keyOf("999"), cv(1, sp("x")))) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || + e.Message != "Row 3 was not saved: 0 rows matched its key (changed or removed by someone else)." { + t.Fatalf("no match: %+v", e) + } + if got := texts(t, s, "SELECT * FROM lq_edit_rb ORDER BY id"); !reflect.DeepEqual(got, before) { + t.Errorf("not rolled back: %q", got) + } + if s.TxState().InTransaction { + t.Error("transaction left open") + } + + // Server errors keep their code. + _, err = apply(s, target, deleteOf("1"), insertOf(cv(0, sp("2")))) + if e := apperr.From(err); e == nil || e.Code != "1062 (23000)" || e.Detail != "Row 2 was not saved." { + t.Errorf("duplicate: %+v", e) + } + if got := texts(t, s, "SELECT * FROM lq_edit_rb ORDER BY id"); !reflect.DeepEqual(got, before) { + t.Errorf("not rolled back after duplicate: %q", got) + } + + // Previews never reach the server. + _, err = apply(s, target, updateOf(keyOf("1"), cv(2, sp("0x0000… (40000 bytes)")))) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid || e.Message != previewMsg { + t.Errorf("preview: %+v", e) + } + if got := first(t, s, "SELECT 1"); got != "1" { + t.Errorf("after: %q", got) + } + run(t, s, "DROP TABLE lq_edit_rb") +} + +func TestMySQLJoinsTheManualTransaction(t *testing.T) { + s := mySession(t) + ctx := context.Background() + run(t, s, "DROP TABLE IF EXISTS lq_edit_tx") + run(t, s, "CREATE TABLE lq_edit_tx (id INT PRIMARY KEY) ENGINE = InnoDB") + target := editable(t, s, "SELECT id FROM lq_edit_tx") + insert := func(id string) model.RowChange { return insertOf(cv(0, sp(id))) } + ids := func(sql string) []string { + var out []string + for _, r := range texts(t, s, sql) { + out = append(out, r[0]) + } + return out + } + + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + run(t, s, "INSERT INTO lq_edit_tx VALUES (10)") + if r, err := apply(s, target, insert("11")); err != nil || !r.InTransaction { + t.Fatalf("apply: %+v %v", r, err) + } + // A failure undoes only this batch; the transaction stays open. + _, err := apply(s, target, insert("12"), deleteOf("999")) + if kindOf(err) != apperr.Database || !s.TxState().InTransaction { + t.Fatalf("failed batch: %v, %+v", err, s.TxState()) + } + if got := ids("SELECT id FROM lq_edit_tx ORDER BY id"); !reflect.DeepEqual(got, []string{"10", "11"}) { + t.Errorf("ids %q", got) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if got := ids("SELECT id FROM lq_edit_tx"); len(got) != 0 { + t.Errorf("after rollback: %q", got) + } + + // First statement of a manual transaction. + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if r, err := apply(s, target, insert("13")); err != nil || !r.InTransaction { + t.Fatalf("first statement: %+v %v", r, err) + } + if _, err := s.EndTransaction(ctx, true); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + + // An explicit transaction in autocommit mode is joined, not committed. + run(t, s, "START TRANSACTION") + if r, err := apply(s, target, insert("14")); err != nil || !r.InTransaction { + t.Fatalf("explicit transaction: %+v %v", r, err) + } + run(t, s, "ROLLBACK") + if got := ids("SELECT id FROM lq_edit_tx"); !reflect.DeepEqual(got, []string{"13"}) { + t.Errorf("ids %q", got) + } + run(t, s, "DROP TABLE lq_edit_tx") +} + +func TestMySQLEditsNamesThatNeedQuoting(t *testing.T) { + s := mySession(t) + run(t, s, "DROP TABLE IF EXISTS `lq_edit_Mixed Case`") + run(t, s, "CREATE TABLE `lq_edit_Mixed Case` (`Order Id` INT NOT NULL PRIMARY KEY, `Some Name` VARCHAR(20))") + run(t, s, "INSERT INTO `lq_edit_Mixed Case` VALUES (1, 'one')") + target := editable(t, s, "SELECT `Some Name` AS label, `Order Id` FROM `lq_edit_Mixed Case`") + if !strings.EqualFold(target.Table, "lq_edit_Mixed Case") || !reflect.DeepEqual(target.Key, []int{1}) || + target.Columns[0].Name != "Some Name" { + t.Errorf("target: %+v", target) + } + + r, err := apply(s, target, + updateOf(keyOf("1"), cv(0, sp("uno")), cv(1, sp("5"))), + insertOf(cv(1, sp("2")), cv(0, sp("two")))) + if err != nil || r.Updated != 1 || r.Inserted != 1 { + t.Fatalf("apply: %+v %v", r, err) + } + if got := texts(t, s, "SELECT * FROM `lq_edit_Mixed Case` ORDER BY 1"); !reflect.DeepEqual(got, + [][]string{{"2", "two"}, {"5", "uno"}}) { + t.Errorf("rows %q", got) + } + if r, err := apply(s, target, deleteOf("5")); err != nil || r.Deleted != 1 { + t.Fatalf("delete: %+v %v", r, err) + } + run(t, s, "DROP TABLE `lq_edit_Mixed Case`") +} + +func TestMySQLResultViewSQL(t *testing.T) { + fixtures.CheckView(t, mySession(t), "mysql") +} + +func TestMySQLDDLSQL(t *testing.T) { + s := mySession(t) + p, _ := myProfile(t) + fixtures.CheckDDL(t, s, "mysql", p.Database) +} diff --git a/internal/drivers/mysql/mysql.go b/internal/drivers/mysql/mysql.go new file mode 100644 index 0000000..0b781a4 --- /dev/null +++ b/internal/drivers/mysql/mysql.go @@ -0,0 +1,1016 @@ +// Package mysql is the MySQL and MariaDB session. +// +// - go-sql-driver opens the connection (dial, TLS, authentication); the +// session then speaks the command phase itself (wire.go), because the +// driver does not expose column origins, status flags or warning counts. +// - Statements run through the text protocol: the server formats every +// value itself, so DECIMAL, DATETIME(6), zero dates and BIGINT UNSIGNED +// arrive exactly as the server prints them. +// - Statements that return rows run with sql_select_limit set to the row +// limit + 1, so the server stops sending rows at the limit; it is +// restored right after. +// - The transaction state comes from the server status flags +// (SERVER_STATUS_IN_TRANS, SERVER_STATUS_AUTOCOMMIT). +// - Warnings are read with SHOW WARNINGS when the statement reports any. +// - Cancel sends KILL QUERY over a separate short-lived connection. +// - Grid editing: see edit.go. +package mysql + +import ( + "context" + "crypto/tls" + "database/sql/driver" + "errors" + "net" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode" + + gomysql "github.com/go-sql-driver/mysql" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + connectTimeout = 15 * time.Second + // cancelGrace is how long a cancelled call waits for the server to stop + // before the connection is cut. + cancelGrace = 15 * time.Second + closedMessage = "The connection to the server was closed." +) + +// Session is one MySQL or MariaDB connection. +type Session struct { + // mu serializes every call except Cancel. + mu sync.Mutex + w *wire + // The driver's connection, kept to close it. + dc driver.Conn + // Opens the connections that send KILL QUERY. + connector driver.Connector + connectionID uint64 + + busy atomic.Bool + cancelRequested atomic.Bool + + stateMu sync.Mutex + state model.TxState + + // Catalog data per (schema, table) for grid editing; cleared by DDL. + catalog map[[2]string]*tableInfo + + engine model.Engine + serverVersion string + currentUser *string + currentSchema *string +} + +var _ drivers.Session = (*Session)(nil) + +// Connect opens a session. password nil means none. +func Connect(ctx context.Context, profile model.ConnectionProfile, password *string) (*Session, error) { + host := strings.TrimSpace(profile.Host) + port := profile.Port + if port == 0 { + port = 3306 + } + cfg := gomysql.NewConfig() + cfg.Net = "tcp" + cfg.Addr = net.JoinHostPort(host, strconv.Itoa(int(port))) + cfg.User = strings.TrimSpace(profile.User) + if password != nil { + cfg.Passwd = *password + } + cfg.DBName = strings.TrimSpace(profile.Database) + cfg.MultiStatements = true + cfg.CheckConnLiveness = false + cfg.ConnectionAttributes = "program_name:LowQuery" + cfg.Logger = &gomysql.NopLogger{} + cfg.Timeout = connectTimeout + dialer := &net.Dialer{KeepAlive: 60 * time.Second} + cfg.DialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) { + return dialer.DialContext(ctx, network, addr) + } + + dc, connector, err := openTLS(ctx, cfg, profile.SslMode, host) + if err != nil { + return nil, apperr.From(err) + } + w, err := takeOver(dc) + if err != nil { + _ = dc.Close() + return nil, err + } + s := &Session{ + w: w, + dc: dc, + connector: connector, + state: model.TxState{Autocommit: true}, + catalog: map[[2]string]*tableInfo{}, + engine: profile.Engine, + } + sets, err := w.textRows("SELECT VERSION(), CURRENT_USER(), DATABASE(), CONNECTION_ID()") + if err != nil { + _ = dc.Close() + e := *mapError(err) + e.Kind = apperr.Connection + return nil, &e + } + var row []*string + if len(sets) > 0 && len(sets[0]) > 0 { + row = sets[0][0] + } + s.serverVersion = productVersion(cellText(row, 0)) + if len(row) > 1 { + s.currentUser = row[1] + } + if len(row) > 2 { + s.currentSchema = row[2] + } + s.connectionID, _ = strconv.ParseUint(cellText(row, 3), 10, 64) + if w.hasStatus { + s.state = txStateFrom(w.status) + } + return s, nil +} + +// openTLS opens the driver connection for the profile's sslMode, like +// libpq: verify-full checks the chain and the host name; prefer and require +// encrypt without validating the certificate, and prefer falls back to +// plain TCP when the server has no TLS or the handshake fails. +func openTLS(ctx context.Context, base *gomysql.Config, mode model.SslMode, host string) (driver.Conn, driver.Connector, error) { + with := func(t *tls.Config, fallback bool) *gomysql.Config { + cfg := base.Clone() + cfg.TLS = t + cfg.AllowFallbackToPlaintext = fallback + return cfg + } + lenient := func() *tls.Config { + return &tls.Config{ServerName: host, InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} + } + switch mode { + case model.SslDisable: + return open(ctx, with(nil, false)) + case model.SslRequire: + return open(ctx, with(lenient(), false)) + case model.SslVerifyFull: + return open(ctx, with(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}, false)) + } + dc, connector, err := open(ctx, with(lenient(), true)) + if err != nil && ctx.Err() == nil && tlsFailed(err) { + return open(ctx, with(nil, false)) + } + return dc, connector, err +} + +// tlsFailed says whether a connection failed in the TLS handshake. +func tlsFailed(err error) bool { + var ce *connectError + if !errors.As(err, &ce) { + return false + } + var header tls.RecordHeaderError + var alert tls.AlertError + var verify *tls.CertificateVerificationError + return errors.As(ce.cause, &header) || errors.As(ce.cause, &alert) || errors.As(ce.cause, &verify) || + errors.Is(ce.cause, gomysql.ErrNoTLS) || strings.HasPrefix(ce.cause.Error(), "tls: ") +} + +// connectError is a failed connection with the driver's error, which +// tlsFailed reads. +type connectError struct { + err *apperr.Error + cause error +} + +func (e *connectError) Error() string { return e.err.Error() } +func (e *connectError) Unwrap() error { return e.err } + +// open opens one driver connection within the connection timeout. +func open(ctx context.Context, cfg *gomysql.Config) (driver.Conn, driver.Connector, error) { + connector, err := gomysql.NewConnector(cfg) + if err != nil { + return nil, nil, apperr.New(apperr.Invalid, err.Error()) + } + dc, err := dial(ctx, connector) + if err != nil { + return nil, nil, err + } + return dc, connector, nil +} + +func dial(ctx context.Context, connector driver.Connector) (driver.Conn, error) { + cctx, cancel := context.WithTimeout(ctx, connectTimeout) + defer cancel() + dc, err := connector.Connect(cctx) + if err == nil { + return dc, nil + } + switch { + case ctx.Err() != nil: + return nil, apperr.CancelledErr() + case cctx.Err() != nil: + return nil, apperr.New(apperr.Connection, "Timed out connecting to the server.") + } + e := *mapError(err) + e.Kind = apperr.Connection + return nil, &connectError{err: &e, cause: err} +} + +func txStateFrom(status uint16) model.TxState { + return model.TxState{ + Autocommit: status&statusAutocommit != 0, + InTransaction: status&statusInTrans != 0, + } +} + +func (s *Session) Engine() model.Engine { return s.engine } +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 closedErr() *apperr.Error { return apperr.New(apperr.Connection, closedMessage) } + +func (s *Session) TxState() model.TxState { + s.stateMu.Lock() + defer s.stateMu.Unlock() + return s.state +} + +// refreshState reads the transaction state from the last OK packet. After +// an error there is none, so a no-op statement fetches fresh flags. +func (s *Session) refreshState() { + if !s.w.hasStatus && !s.w.isBroken() { + _, _ = s.w.exec("DO 0") + } + if s.w.hasStatus { + s.stateMu.Lock() + s.state = txStateFrom(s.w.status) + s.stateMu.Unlock() + } +} + +// mapError turns protocol and driver errors into the app error: server +// errors keep their number and SQLSTATE, as "1045 (28000)". +func mapError(err error) *apperr.Error { + var ae *apperr.Error + if errors.As(err, &ae) { + return ae + } + var se *serverError + if errors.As(err, &se) { + return fromServer(se.code, se.state, se.message) + } + var me *gomysql.MySQLError + if errors.As(err, &me) { + state := "" + if me.SQLState != [5]byte{} { + state = string(me.SQLState[:]) + } + return fromServer(me.Number, state, me.Message) + } + switch { + case errors.Is(err, errClosed), errors.Is(err, driver.ErrBadConn), errors.Is(err, gomysql.ErrInvalidConn): + return closedErr() + case errors.Is(err, errMalformed): + return apperr.New(apperr.Connection, "The server sent a packet LowQuery cannot read.") + } + return apperr.New(apperr.Connection, err.Error()) +} + +func fromServer(code uint16, state, message string) *apperr.Error { + kind := apperr.Database + if code == queryInterrupted { + kind = apperr.Cancelled + } + e := &apperr.Error{Kind: kind, Message: strings.TrimRightFunc(message, unicode.IsSpace)} + if state == "" { + e.Code = strconv.Itoa(int(code)) + } else { + e.Code = strconv.Itoa(int(code)) + " (" + state + ")" + } + return e +} + +// watch sends KILL QUERY when ctx is done before the returned stop is +// called. If the server does not stop within cancelGrace, the connection +// is cut. +func (s *Session) watch(ctx context.Context) (stop func()) { + if ctx.Done() == nil { + return func() {} + } + done := make(chan struct{}) + finished := make(chan struct{}) + go func() { + defer close(finished) + select { + case <-done: + return + case <-ctx.Done(): + } + _ = s.kill(context.Background()) + select { + case <-done: + case <-time.After(cancelGrace): + s.w.cut() + } + }() + return func() { + close(done) + <-finished + } +} + +// kill sends KILL QUERY for this session's connection from a new one. +func (s *Session) kill(ctx context.Context) error { + s.cancelRequested.Store(true) + dc, err := dial(ctx, s.connector) + if err != nil { + return apperr.From(err) + } + defer func() { _ = dc.Close() }() + execer, ok := dc.(driver.ExecerContext) + if !ok { + return apperr.Internalf("The MySQL driver cannot run statements.") + } + kctx, cancel := context.WithTimeout(ctx, connectTimeout) + defer cancel() + if _, err := execer.ExecContext(kctx, "KILL QUERY "+strconv.FormatUint(s.connectionID, 10), nil); err != nil { + return mapError(err) + } + return nil +} + +func (s *Session) Cancel(ctx context.Context) error { + if !s.busy.Load() { + return nil + } + return s.kill(ctx) +} + +// begin locks the session for a call that may be cancelled through ctx. +// end unlocks it after refreshing the transaction state. +func (s *Session) begin(ctx context.Context) (end func(), err error) { + s.mu.Lock() + if s.w.isBroken() { + s.mu.Unlock() + return nil, closedErr() + } + s.cancelRequested.Store(false) + s.busy.Store(true) + stop := s.watch(ctx) + return func() { + s.busy.Store(false) + stop() + s.refreshState() + s.mu.Unlock() + }, nil +} + +// cancelled replaces the error of a call stopped through ctx. +func cancelled(ctx context.Context, err error) error { + if ctx.Err() != nil { + if k := apperr.From(err).Kind; k == apperr.Connection || k == apperr.Cancelled { + return apperr.CancelledErr() + } + } + return err +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + result, err := s.run(ctx, req) + end() + if err != nil { + return nil, cancelled(ctx, err) + } + if result.Columns != nil && s.cancelRequested.Swap(false) { + // SELECT SLEEP(n) interrupted by KILL QUERY returns a row instead + // of an error. + return nil, &apperr.Error{ + Kind: apperr.Cancelled, + Message: "Query execution was interrupted", + Code: strconv.Itoa(queryInterrupted) + " (70100)", + } + } + result.InTransaction = s.TxState().InTransaction + result.Normalize() + return result, nil +} + +type collected struct { + columns []column + rows []model.Row + truncated bool + affected *uint64 + warnings uint16 +} + +func (s *Session) run(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + sql := prepareSQL(req.SQL) + limit := req.MaxRows > 0 && isSelectLike(sql) + if limit { + if _, err := s.w.exec("SET SESSION sql_select_limit = " + strconv.FormatUint(uint64(req.MaxRows)+1, 10)); err != nil { + return nil, mapError(err) + } + } + + started := time.Now() + out, err := s.readResults(sql, req.MaxRows, drivers.BinaryLimit(ctx, binaryPreviewBytes)) + elapsed := uint64(time.Since(started).Milliseconds()) + + var notices []string + if err == nil && out.warnings > 0 { + notices = s.readWarnings() + } + if limit { + _, _ = s.w.exec("SET SESSION sql_select_limit = DEFAULT") + } + if isDDL(sql) { + clear(s.catalog) + } + if err != nil { + e := *mapError(err) + if e.Kind == apperr.Database { + e.Position = errorPosition(sql, e.Message) + } + return nil, &e + } + + result := &model.ExecResult{ + Rows: out.rows, + Truncated: out.truncated, + RowsAffected: out.affected, + ElapsedMs: elapsed, + Notices: notices, + } + if out.columns != nil { + result.Columns = columnInfos(out.columns) + if !s.cancelRequested.Load() { + if target, reason := s.detectTarget(sql, out.columns); target != nil { + result.Editable = target + } else { + result.ReadOnlyReason = &reason + } + } + } + return result, nil +} + +// readResults reads every result: the first one with columns is kept (up +// to maxRows), the others are drained; affected rows are summed. +func (s *Session) readResults(sql string, maxRows, binaryLimit int) (*collected, error) { + resp, err := s.w.query(sql) + if err != nil { + return nil, err + } + out := &collected{} + for { + more, err := resp.next() + if err != nil { + return nil, err + } + if !more { + break + } + if resp.columns == nil { + n := resp.ok.affected + if out.affected != nil { + n += *out.affected + } + out.affected = &n + out.warnings = max(out.warnings, resp.ok.warnings) + continue + } + keep := out.columns == nil + if keep { + out.columns = resp.columns + out.rows = []model.Row{} + } + for { + values, err := resp.row() + if err != nil { + return nil, err + } + if values == nil { + break + } + if !keep { + continue + } + if maxRows > 0 && len(out.rows) >= maxRows { + out.truncated = true + continue + } + out.rows = append(out.rows, formatRow(resp.columns, values, binaryLimit)) + } + out.warnings = max(out.warnings, resp.ok.warnings) + } + if resp.localInfile { + return nil, apperr.New(apperr.Invalid, "LowQuery does not send local files (LOAD DATA LOCAL INFILE).") + } + return out, nil +} + +// readWarnings returns "Level Code: Message" lines from SHOW WARNINGS. +func (s *Session) readWarnings() []string { + sets, err := s.w.textRows("SHOW WARNINGS LIMIT " + strconv.Itoa(maxWarnings)) + if err != nil || len(sets) == 0 { + return nil + } + out := make([]string, 0, len(sets[0])) + for _, r := range sets[0] { + out = append(out, cellText(r, 0)+" "+cellText(r, 1)+": "+cellText(r, 2)) + } + return out +} + +// detectTarget is the editable target of a row-returning result, or why it +// is read-only. Catalog errors end in a read-only reason, never in a failed +// query. +func (s *Session) detectTarget(sql string, columns []column) (*model.EditTarget, string) { + if !mayBeEditable(sql) { + return nil, notATable + } + origins := make([]*origin, len(columns)) + for i, c := range columns { + origins[i] = originOf(c) + } + schema, table, reason := singleTable(origins) + if reason != "" { + return nil, reason + } + info, err := s.tableInfo(schema, table) + if err != nil { + return nil, unknownTable + } + return editTarget(schema, table, info, origins) +} + +// tableInfo returns the table type, columns and unique keys, cached per +// session. +func (s *Session) tableInfo(schema, table string) (*tableInfo, error) { + key := [2]string{schema, table} + if info := s.catalog[key]; info != nil { + return info, nil + } + sets, err := s.w.textRows(catalogSQL(schema, table)) + if err != nil { + return nil, err + } + for len(sets) < 3 { + sets = append(sets, nil) + } + info := tableInfoFrom(sets[0], sets[1], sets[2]) + if len(s.catalog) >= 256 { + clear(s.catalog) + } + s.catalog[key] = info + return info, nil +} + +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + // Turning autocommit on commits the open transaction (server rule). + if on { + return s.control(ctx, "SET autocommit = 1") + } + return s.control(ctx, "SET autocommit = 0") +} + +func (s *Session) EndTransaction(ctx context.Context, commit bool) (model.TxState, error) { + if commit { + return s.control(ctx, "COMMIT") + } + return s.control(ctx, "ROLLBACK") +} + +func (s *Session) control(ctx context.Context, sql string) (model.TxState, error) { + end, err := s.begin(ctx) + if err != nil { + return s.TxState(), err + } + _, err = s.w.exec(sql) + end() + if err != nil { + return s.TxState(), cancelled(ctx, mapError(err)) + } + return s.TxState(), nil +} + +// textRows runs a metadata query, binding values as string literals, and +// returns the rows of its first result set. +func (s *Session) textRows(sql string, values ...string) ([][]*string, error) { + sets, err := s.w.textRows(bindLiterals(sql, values...)) + if err != nil { + return nil, mapError(err) + } + if len(sets) == 0 { + return nil, nil + } + return sets[0], nil +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + current, err := s.textRows("SELECT DATABASE()") + if err != nil { + return nil, cancelled(ctx, err) + } + cur := "" + if len(current) > 0 { + cur = cellText(current[0], 0) + } + rows, err := s.textRows("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA") + if err != nil { + return nil, cancelled(ctx, err) + } + names := make([]string, len(rows)) + for i, r := range rows { + names[i] = cellText(r, 0) + } + rank := func(n string) int { + switch { + case n == cur: + return 0 + case isSystemSchema(n): + return 2 + } + return 1 + } + sort.SliceStable(names, func(i, j int) bool { + ri, rj := rank(names[i]), rank(names[j]) + if ri != rj { + return ri < rj + } + return strings.ToLower(names[i]) < strings.ToLower(names[j]) + }) + return names, 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 TABLE_NAME, + CASE TABLE_TYPE WHEN 'VIEW' THEN 'view' WHEN 'SYSTEM VIEW' THEN 'view' + WHEN 'SEQUENCE' THEN 'sequence' ELSE 'table' END + FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? + UNION ALL + SELECT ROUTINE_NAME, CASE ROUTINE_TYPE WHEN 'FUNCTION' THEN 'function' + ELSE 'procedure' END + FROM information_schema.ROUTINES + WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE IN ('FUNCTION', 'PROCEDURE')`, schema, schema) + if err != nil { + return nil, cancelled(ctx, err) + } + out := make([]model.DbObject, len(rows)) + for i, r := range rows { + out[i] = model.DbObject{Name: cellText(r, 0), Kind: cellText(r, 1)} + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Kind != out[j].Kind { + return out[i].Kind < out[j].Kind + } + return out[i].Name < out[j].Name + }) + 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 COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, + COLUMN_DEFAULT IS NULL, COLUMN_DEFAULT, EXTRA + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? + ORDER BY ORDINAL_POSITION`, schema, table) + if err != nil { + return nil, cancelled(ctx, err) + } + mariadb := s.engine == model.MariaDB + out := make([]model.DbColumn, len(rows)) + for i, r := range rows { + c := model.DbColumn{ + Name: cellText(r, 0), + TypeName: cellText(r, 1), + Nullable: cellText(r, 2) == "YES", + PrimaryKey: cellText(r, 3) == "PRI", + } + if cellText(r, 4) == "0" { + c.DefaultValue = defaultExpr(cellText(r, 5), cellText(r, 6), mariadb) + } + out[i] = c + } + return out, nil +} + +// ObjectDDL is the SHOW CREATE output, with routines and triggers between +// DELIMITER lines so the script runs as written. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + var what string + column := 1 + switch kind { + case "table": + what = "TABLE" + case "view": + what = "VIEW" + case "sequence": + what = "SEQUENCE" + case "function": + what, column = "FUNCTION", 2 + case "procedure": + what, column = "PROCEDURE", 2 + default: + return "", apperr.Invalidf("LowQuery cannot script a %s on this server.", kind) + } + end, err := s.begin(ctx) + if err != nil { + return "", err + } + defer end() + target := quoteIdent(schema) + "." + quoteIdent(name) + def, err := s.showCreate("SHOW CREATE "+what+" "+target, column) + if err != nil { + return "", cancelled(ctx, err) + } + if strings.TrimSpace(def) == "" { + return def, nil + } + var out strings.Builder + if kind == "function" || kind == "procedure" { + out.WriteString("DELIMITER $$\n" + def + "$$\nDELIMITER ;\n") + } else { + out.WriteString(def + ";\n") + } + if kind == "table" { + triggers, err := s.textRows(`SELECT TRIGGER_NAME FROM information_schema.TRIGGERS + WHERE EVENT_OBJECT_SCHEMA = ? AND EVENT_OBJECT_TABLE = ? + ORDER BY ACTION_ORDER, TRIGGER_NAME`, schema, name) + if err != nil { + return "", cancelled(ctx, err) + } + if len(triggers) > 0 { + out.WriteString("\nDELIMITER $$\n") + for _, t := range triggers { + sql := "SHOW CREATE TRIGGER " + quoteIdent(schema) + "." + quoteIdent(cellText(t, 0)) + def, err := s.showCreate(sql, 2) + if err != nil { + return "", cancelled(ctx, err) + } + out.WriteString(def + "$$\n") + } + out.WriteString("DELIMITER ;\n") + } + } + return out.String(), nil +} + +// showCreate is one column of a SHOW CREATE ... row. +func (s *Session) showCreate(sql string, column int) (string, error) { + rows, err := s.textRows(sql) + if err != nil { + return "", err + } + if len(rows) == 0 { + return "", nil + } + return cellText(rows[0], column), nil +} + +// Stream reads the rows of a query as the server sends them, in batches. +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 + } + total, err := s.stream(ctx, sql, sink) + end() + if err != nil { + return total, cancelled(ctx, err) + } + return total, nil +} + +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) { + resp, err := s.w.query(sql) + if err != nil { + return 0, mapError(err) + } + more, err := resp.next() + if err != nil { + return 0, mapError(err) + } + if !more || resp.columns == nil { + if err := resp.drain(); err != nil { + return 0, mapError(err) + } + return 0, apperr.New(apperr.Invalid, "The statement returns no rows.") + } + // The watcher sends KILL QUERY once ctx is done; what the server still + // sends is read and dropped. + stopped := func() error { + _ = resp.drain() + return apperr.CancelledErr() + } + cols := resp.columns + if !send(ctx, sink, drivers.StreamEvent{Columns: columnInfos(cols)}) { + return 0, stopped() + } + limit := drivers.BinaryLimit(drivers.WithFullValues(ctx), binaryPreviewBytes) + var total uint64 + batch := make([]model.Row, 0, drivers.StreamBatch) + for { + values, err := resp.row() + if err != nil { + return total, mapError(err) + } + if values == nil { + break + } + batch = append(batch, formatRow(cols, values, limit)) + total++ + if len(batch) == drivers.StreamBatch { + if !send(ctx, sink, drivers.StreamEvent{Rows: batch}) { + return total, stopped() + } + batch = make([]model.Row, 0, drivers.StreamBatch) + } + } + if err := resp.drain(); err != nil { + return total, mapError(err) + } + if len(batch) > 0 && !send(ctx, sink, drivers.StreamEvent{Rows: batch}) { + return total, apperr.CancelledErr() + } + return total, nil +} + +// ApplyChanges applies grid edits. With autocommit on they run in their own +// transaction; otherwise they join the session's transaction behind a +// savepoint, so a failure undoes only them and the transaction stays open. +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + // Bad input is rejected before anything runs. + statements := make([]*statement, len(req.Changes)) + for i, c := range req.Changes { + st, err := buildChange(&req.Target, s.engine, c) + if err != nil { + return nil, atRow(err, i) + } + statements[i] = st + } + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + state := s.TxState() + own := state.Autocommit && !state.InTransaction + started := time.Now() + result, err := s.applyInTransaction(&req, statements, own) + end() + if err != nil { + return nil, cancelled(ctx, err) + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.InTransaction = s.TxState().InTransaction + return result, nil +} + +// applyInTransaction runs the changes between START TRANSACTION and COMMIT +// (own) or inside a savepoint of the open transaction; any error undoes +// them all. +func (s *Session) applyInTransaction(req *model.ApplyRequest, statements []*statement, own bool) (*model.ApplyResult, error) { + begin := "SAVEPOINT " + savepoint + if own { + begin = "START TRANSACTION" + } + if _, err := s.w.exec(begin); err != nil { + return nil, mapError(err) + } + result, err := s.runChanges(req, statements) + var endSQL string + switch { + case err == nil && own: + endSQL = "COMMIT" + case err == nil: + endSQL = "RELEASE SAVEPOINT " + savepoint + case own: + endSQL = "ROLLBACK" + default: + endSQL = "ROLLBACK TO SAVEPOINT " + savepoint + } + _, endErr := s.w.exec(endSQL) + if err != nil { + if !own { + _, _ = s.w.exec("RELEASE SAVEPOINT " + savepoint) + } + return nil, err + } + if endErr != nil { + if own { + _, _ = s.w.exec("ROLLBACK") + } + return nil, mapError(endErr) + } + return result, nil +} + +func (s *Session) runChanges(req *model.ApplyRequest, statements []*statement) (*model.ApplyResult, error) { + out := &model.ApplyResult{} + for i, st := range statements { + if st == nil { + continue + } + change := req.Changes[i] + ok, _, err := s.w.runPrepared(st.sql, st.params) + if err != nil { + return nil, atRow(mapError(err), i) + } + switch change.Op { + case model.OpInsert: + out.Inserted++ + case model.OpDelete: + if err := checkMatched(i, ok.affected); err != nil { + return nil, err + } + out.Deleted++ + case model.OpUpdate: + matched := ok.affected + if matched != 1 { + // Unchanged values: ask how many rows the key matched. + if n, found := matchedRows(ok.info); found { + matched = n + } else if matched, err = s.countRows(&req.Target, change.Key); err != nil { + return nil, atRow(err, i) + } + } + if err := checkMatched(i, matched); err != nil { + return nil, err + } + out.Updated++ + } + } + return out, nil +} + +// countRows counts the rows with the given key (an UPDATE that changed +// nothing left it as is). +func (s *Session) countRows(target *model.EditTarget, key []*string) (uint64, error) { + var sb strings.Builder + sb.WriteString("SELECT COUNT(*) FROM " + tableRef(target)) + var params []param + if err := pushWhere(&sb, ¶ms, target, s.engine, key); err != nil { + return 0, err + } + _, sets, err := s.w.runPrepared(sb.String(), params) + if err != nil { + return 0, mapError(err) + } + if len(sets) == 0 || len(sets[0]) == 0 { + return 0, nil + } + n, _ := strconv.ParseUint(cellText(sets[0][0], 0), 10, 64) + return n, nil +} + +// Close closes the connection; a running call is interrupted. +func (s *Session) Close() error { + if !s.mu.TryLock() { + _ = s.w.nc.Close() + s.mu.Lock() + } + defer s.mu.Unlock() + broken := s.w.isBroken() + s.w.broken.Store(true) + // The driver sends COM_QUIT and closes the socket. + err := s.dc.Close() + if broken { + return nil + } + return err +} diff --git a/internal/drivers/mysql/session_test.go b/internal/drivers/mysql/session_test.go new file mode 100644 index 0000000..c767d54 --- /dev/null +++ b/internal/drivers/mysql/session_test.go @@ -0,0 +1,464 @@ +package mysql + +// Session tests against the scripted server in fake_test.go: the real +// go-sql-driver handshake, the takeover of its connection and the command +// phase, with and without CLIENT_DEPRECATE_EOF. + +import ( + "context" + "reflect" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func fakeProfile(port uint16) model.ConnectionProfile { + p := model.DefaultProfile() + p.Engine = model.MySQL + p.Host = "127.0.0.1" + p.Port = port + p.User = "root" + p.Database = "app" + p.SslMode = model.SslPrefer + return p +} + +func connectFake(t *testing.T, srv *fakeServer) *Session { + t.Helper() + s, err := Connect(context.Background(), fakeProfile(srv.port()), nil) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +// cells shows a row with NULL as "NULL". +func cells(row model.Row) []string { + out := make([]string, len(row)) + for i, v := range row { + if v == nil { + out[i] = "NULL" + } else { + out[i] = *v + } + } + return out +} + +func sameCommands(t *testing.T, got []string, want ...string) { + t.Helper() + if !reflect.DeepEqual(got, want) { + t.Errorf("commands:\n got %q\nwant %q", got, want) + } +} + +const sessionSQL = "SELECT VERSION(), CURRENT_USER(), DATABASE(), CONNECTION_ID()" + +func answerSession(c *fakeConn) { + c.result([]fakeCol{expr("VERSION()", typeVarString), expr("CURRENT_USER()", typeVarString), + expr("DATABASE()", typeVarString), expr("CONNECTION_ID()", typeLongLong)}, + [][]string{{"8.4.2", "root@%", "app", "7"}}, 0, false) +} + +func TestSessionOverFakeServer(t *testing.T) { + t.Run("deprecate-eof", func(t *testing.T) { sessionScenario(t, true, false) }) + t.Run("eof", func(t *testing.T) { sessionScenario(t, false, false) }) + t.Run("mariadb", func(t *testing.T) { sessionScenario(t, true, true) }) +} + +func sessionScenario(t *testing.T, deprecateEOF, mariadb bool) { + blob := fakeCol{schema: "app", table: "t", orgTable: "t", name: "b", orgName: "b", typ: typeBlob, charset: 63} + big := strings.Repeat("\xab", 40000) + var srv *fakeServer + srv = newFakeServer(t, deprecateEOF, func(c *fakeConn, sql string) { + ok := func() { c.ok(0, "", false) } + switch { + case sql == sessionSQL && mariadb: + c.result([]fakeCol{expr("VERSION()", typeVarString), expr("CURRENT_USER()", typeVarString), + expr("DATABASE()", typeVarString), expr("CONNECTION_ID()", typeLongLong)}, + [][]string{{"11.4.2-MariaDB-ubu2404", "root@%", "app", "7"}}, 0, false) + case sql == sessionSQL: + answerSession(c) + case strings.HasPrefix(sql, "SET SESSION sql_select_limit"), sql == "DO 0": + ok() + case sql == "SELECT id, name, id * 2 AS dbl, b FROM t": + c.result([]fakeCol{tcol("id", "id", typeLong), tcol("name", "name", typeVarString), + expr("dbl", typeLongLong), blob}, + [][]string{{"1", "a", "2", "\x00\xff"}, {"2", nullValue, "4", ""}, {"3", "c", "6", "x"}}, 1, false) + case sql == "SHOW WARNINGS LIMIT 100": + c.result([]fakeCol{expr("Level", typeVarString), expr("Code", typeLong), expr("Message", typeVarString)}, + [][]string{{"Warning", "1292", "Truncated incorrect value"}}, 0, false) + case sql == catalogSQL("app", "t"): + c.result([]fakeCol{expr("TABLE_TYPE", typeVarString)}, [][]string{{"BASE TABLE"}}, 0, true) + c.result([]fakeCol{expr("COLUMN_NAME", typeVarString), expr("COLUMN_TYPE", typeBlob), + expr("IS_NULLABLE", typeVarString), expr("EXTRA", typeVarString)}, + [][]string{{"id", "int", "NO", "auto_increment"}, {"name", "varchar(20)", "YES", ""}, + {"b", "blob", "YES", ""}}, 0, true) + c.result([]fakeCol{expr("INDEX_NAME", typeVarString), expr("COLUMN_NAME", typeVarString)}, + [][]string{{"PRIMARY", "id"}}, 0, false) + case sql == "UPDATE t SET name = name; SELECT 1": + c.ok(3, "Rows matched: 3 Changed: 0 Warnings: 0", true) + c.result([]fakeCol{expr("1", typeLongLong)}, [][]string{{"1"}}, 0, false) + case sql == "SELECT *\nFROMM x": + c.fail(1064, "42000", "You have an error in your SQL syntax; check the manual that corresponds "+ + "to your MySQL server version for the right syntax to use near 'FROMM x' at line 2") + case sql == "SET autocommit = 0": + c.status = 0 + ok() + case sql == "SET autocommit = 1": + c.status = statusAutocommit + ok() + case sql == "INSERT INTO t VALUES (9)": + c.status |= statusInTrans + c.ok(1, "", false) + case sql == "START TRANSACTION": + c.status |= statusInTrans + ok() + case sql == "ROLLBACK", sql == "COMMIT": + c.status &^= statusInTrans + ok() + case sql == "EXECUTE UPDATE `app`.`t` SET `name` = ? WHERE `id` = ? [\"a\", \"1\"]": + c.ok(0, "Rows matched: 1 Changed: 0 Warnings: 0", false) + case sql == "EXECUTE UPDATE `app`.`t` SET `name` = ? WHERE `id` = ? [\"z\", \"5\"]": + c.ok(0, "", false) + case sql == "EXECUTE SELECT COUNT(*) FROM `app`.`t` WHERE `id` = ? [\"5\"]": + c.countResult(0) + case sql == "SELECT n, b FROM big": + rows := make([][]string, 1234) + for i := range rows { + rows[i] = []string{"1", nullValue} + } + rows[1][1] = big + c.result([]fakeCol{expr("n", typeLong), blob}, rows, 0, false) + case sql == "SELECT DATABASE()": + c.result([]fakeCol{expr("DATABASE()", typeVarString)}, [][]string{{"app"}}, 0, false) + case sql == "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA": + c.result([]fakeCol{expr("SCHEMA_NAME", typeVarString)}, + [][]string{{"mysql"}, {"zeta"}, {"app"}, {"Alpha"}, {"sys"}}, 0, false) + case strings.Contains(sql, "FROM information_schema.COLUMNS") && + strings.Contains(sql, "TABLE_SCHEMA = "+stringLiteral("app")+" AND TABLE_NAME = "+stringLiteral("t")): + c.result([]fakeCol{expr("COLUMN_NAME", typeVarString), expr("COLUMN_TYPE", typeBlob), + expr("IS_NULLABLE", typeVarString), expr("COLUMN_KEY", typeVarString), + expr("COLUMN_DEFAULT IS NULL", typeLongLong), expr("COLUMN_DEFAULT", typeBlob), + expr("EXTRA", typeVarString)}, + [][]string{{"id", "int", "NO", "PRI", "1", nullValue, "auto_increment"}, + {"name", "varchar(20)", "YES", "", "0", "x", ""}}, 0, false) + case sql == "SHOW CREATE PROCEDURE `app`.`p`": + c.result([]fakeCol{expr("Procedure", typeVarString), expr("sql_mode", typeVarString), + expr("Create Procedure", typeBlob)}, + [][]string{{"p", "", "CREATE PROCEDURE `p`()\nSELECT 1"}}, 0, false) + default: + srv.t.Errorf("unexpected statement %q", sql) + c.fail(1064, "42000", "unexpected statement") + } + }) + + srv.mariadb.Store(mariadb) + profile := fakeProfile(srv.port()) + version, defaultX := "MySQL 8.4.2", "'x'" + if mariadb { + profile.Engine = model.MariaDB + // MariaDB writes COLUMN_DEFAULT as SQL already. + version, defaultX = "MariaDB 11.4.2", "x" + } + s, err := Connect(context.Background(), profile, nil) + if err != nil { + t.Fatalf("connect: %v", err) + } + defer func() { _ = s.Close() }() + if s.w.cacheMetadata != mariadb || s.w.deprecateEOF != deprecateEOF { + t.Fatalf("capabilities: cache metadata %v, deprecate EOF %v", s.w.cacheMetadata, s.w.deprecateEOF) + } + ctx := context.Background() + sameCommands(t, srv.take(), sessionSQL) + if s.ServerVersion() != version || *s.CurrentUser() != "root@%" || *s.CurrentSchema() != "app" { + t.Errorf("session: %q %q %q", s.ServerVersion(), *s.CurrentUser(), *s.CurrentSchema()) + } + if s.TxState() != (model.TxState{Autocommit: true}) || s.Engine() != profile.Engine || s.connectionID != 7 { + t.Errorf("state %+v, engine %s, id %d", s.TxState(), s.Engine(), s.connectionID) + } + + // Row limit, warnings, values and the editable target. + query := "SELECT id, name, id * 2 AS dbl, b FROM t" + r, err := s.Execute(ctx, model.ExecRequest{SQL: query + " ;\n", MaxRows: 2}) + if err != nil { + t.Fatal(err) + } + sameCommands(t, srv.take(), "SET SESSION sql_select_limit = 3", query, "SHOW WARNINGS LIMIT 100", + "SET SESSION sql_select_limit = DEFAULT", catalogSQL("app", "t")) + if len(r.Rows) != 2 || !r.Truncated || r.RowsAffected != nil { + t.Fatalf("rows %d, truncated %v, affected %v", len(r.Rows), r.Truncated, r.RowsAffected) + } + if got := cells(r.Rows[0]); !reflect.DeepEqual(got, []string{"1", "a", "2", "0x00FF"}) { + t.Errorf("row 1: %q", got) + } + if got := cells(r.Rows[1]); !reflect.DeepEqual(got, []string{"2", "NULL", "4", "0x"}) { + t.Errorf("row 2: %q", got) + } + wantCols := []model.ColumnInfo{ + {Name: "id", TypeName: "INT", Kind: model.KindNumber}, + {Name: "name", TypeName: "VARCHAR", Kind: model.KindText}, + {Name: "dbl", TypeName: "BIGINT", Kind: model.KindNumber}, + {Name: "b", TypeName: "BLOB", Kind: model.KindBinary}, + } + if !reflect.DeepEqual(r.Columns, wantCols) { + t.Errorf("columns: %+v", r.Columns) + } + if !reflect.DeepEqual(r.Notices, []string{"Warning 1292: Truncated incorrect value"}) { + t.Errorf("notices: %q", r.Notices) + } + target := r.Editable + if target == nil { + t.Fatalf("not editable: %v", strOrNil(r.ReadOnlyReason)) + } + if *target.Schema != "app" || target.Table != "t" || !reflect.DeepEqual(target.Key, []int{0}) || + target.Columns[2] != nil || target.Columns[3].TypeName != "blob" { + t.Errorf("target: %+v", target) + } + // The catalog is cached. + if _, err := s.Execute(ctx, model.ExecRequest{SQL: query}); err != nil { + t.Fatal(err) + } + sameCommands(t, srv.take(), query, "SHOW WARNINGS LIMIT 100") + + // Several results: affected rows of the statements without rows. + r, err = s.Execute(ctx, model.ExecRequest{SQL: "UPDATE t SET name = name; SELECT 1", MaxRows: 10}) + if err != nil { + t.Fatal(err) + } + if r.RowsAffected == nil || *r.RowsAffected != 3 || len(r.Rows) != 1 || *r.Rows[0][0] != "1" || + strOrNil(r.ReadOnlyReason) != notATable || len(r.Notices) != 0 { + t.Errorf("multi: %+v", r) + } + srv.take() + + // Errors keep their code and position; the state is read again. + _, err = s.Execute(ctx, model.ExecRequest{SQL: "SELECT *\nFROMM x;"}) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || e.Code != "1064 (42000)" || e.Position == nil || *e.Position != 9 { + t.Fatalf("error: %+v", e) + } + sameCommands(t, srv.take(), "SELECT *\nFROMM x", "DO 0") + + // Manual transactions follow the server status flags. + st, err := s.SetAutocommit(ctx, false) + if err != nil || st != (model.TxState{}) { + t.Fatalf("autocommit off: %+v %v", st, err) + } + r, err = s.Execute(ctx, model.ExecRequest{SQL: "INSERT INTO t VALUES (9)", MaxRows: 10}) + if err != nil || !r.InTransaction || *r.RowsAffected != 1 || r.Columns != nil || r.ReadOnlyReason != nil { + t.Fatalf("insert: %+v %v", r, err) + } + if st, err := s.EndTransaction(ctx, false); err != nil || st.InTransaction { + t.Fatalf("rollback: %+v %v", st, err) + } + if st, err := s.SetAutocommit(ctx, true); err != nil || st != (model.TxState{Autocommit: true}) { + t.Fatalf("autocommit on: %+v %v", st, err) + } + srv.take() + + // Grid edits run as prepared statements in their own transaction. + res, err := s.ApplyChanges(ctx, model.ApplyRequest{Target: *target, Changes: []model.RowChange{ + {Op: model.OpUpdate, Key: []*string{sp("1")}, Values: []model.CellValue{cv(1, sp("a"))}}, + }}) + if err != nil || res.Updated != 1 || res.InTransaction { + t.Fatalf("apply: %+v %v", res, err) + } + sameCommands(t, srv.take(), "START TRANSACTION", "PREPARE UPDATE `app`.`t` SET `name` = ? WHERE `id` = ?", + `EXECUTE "a", "1"`, "CLOSE 1", "COMMIT") + _, err = s.ApplyChanges(ctx, model.ApplyRequest{Target: *target, Changes: []model.RowChange{ + {Op: model.OpUpdate, Key: []*string{sp("5")}, Values: []model.CellValue{cv(1, sp("z"))}}, + }}) + if e := apperr.From(err); e == nil || e.Kind != apperr.Database || + e.Message != "Row 1 was not saved: 0 rows matched its key (changed or removed by someone else)." { + t.Fatalf("apply without a match: %+v", e) + } + sameCommands(t, srv.take(), "START TRANSACTION", "PREPARE UPDATE `app`.`t` SET `name` = ? WHERE `id` = ?", + `EXECUTE "z", "5"`, "CLOSE 2", "PREPARE SELECT COUNT(*) FROM `app`.`t` WHERE `id` = ?", `EXECUTE "5"`, + "CLOSE 3", "ROLLBACK") + if s.TxState().InTransaction { + t.Error("transaction left open") + } + + // Stream: columns, then batches with values in full. + sink := make(chan drivers.StreamEvent, 10) + total, err := s.Stream(ctx, "SELECT n, b FROM big", sink) + close(sink) + if err != nil || total != 1234 { + t.Fatalf("stream: %d %v", total, err) + } + 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[1][1]; len(v) != 2+80000 || strings.Contains(v, "…") { + t.Errorf("binary value not in full: %d characters", len(v)) + } + srv.take() + + // Metadata. + schemas, err := s.ListSchemas(ctx) + if err != nil || !reflect.DeepEqual(schemas, []string{"app", "Alpha", "zeta", "mysql", "sys"}) { + t.Errorf("schemas: %q %v", schemas, err) + } + cols, err := s.ListColumns(ctx, "app", "t") + if err != nil || len(cols) != 2 || !cols[0].PrimaryKey || cols[0].Nullable || cols[0].DefaultValue != nil || + !cols[1].Nullable || strOrNil(cols[1].DefaultValue) != defaultX { + t.Errorf("columns: %+v %v", cols, err) + } + ddl, err := s.ObjectDDL(ctx, "app", "p", "procedure") + if err != nil || ddl != "DELIMITER $$\nCREATE PROCEDURE `p`()\nSELECT 1$$\nDELIMITER ;\n" { + t.Errorf("ddl: %q %v", ddl, err) + } + if _, err := s.ObjectDDL(ctx, "app", "x", "package"); kindOf(err) != apperr.Invalid { + t.Errorf("package: %v", err) + } + srv.take() + + if err := s.Close(); err != nil { + t.Fatal(err) + } + waitFor(t, srv.quit, "COM_QUIT") +} + +func TestCancelOverFakeServer(t *testing.T) { + started := make(chan struct{}, 2) + var srv *fakeServer + srv = newFakeServer(t, true, func(c *fakeConn, sql string) { + switch sql { + case sessionSQL: + answerSession(c) + case "SET SESSION sql_select_limit = 11", "SET SESSION sql_select_limit = DEFAULT": + c.ok(0, "", false) + case "SELECT SLEEP(30)": + started <- struct{}{} + // Interrupted, SLEEP returns 1 instead of an error. + if !signalled(srv.killed) { + srv.t.Error("timed out waiting for KILL QUERY") + } + c.result([]fakeCol{expr("SLEEP(30)", typeLongLong)}, [][]string{{"1"}}, 0, false) + case "SELECT 2": + c.result([]fakeCol{expr("2", typeLongLong)}, [][]string{{"2"}}, 0, false) + default: + srv.t.Errorf("unexpected statement %q", sql) + c.fail(1064, "42000", "unexpected statement") + } + }) + s := connectFake(t, srv) + if err := s.Cancel(context.Background()); err != nil { + t.Fatalf("cancel while idle: %v", err) + } + + check := func(err error) { + t.Helper() + e := apperr.From(err) + if e == nil || e.Kind != apperr.Cancelled || e.Code != "1317 (70100)" { + t.Fatalf("error %+v", e) + } + r, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT 2", MaxRows: 10}) + if err != nil || *r.Rows[0][0] != "2" { + t.Fatalf("after cancel: %v", err) + } + } + + // Cancel from another goroutine. + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT SLEEP(30)", MaxRows: 10}) + done <- err + }() + waitFor(t, started, "the query") + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + check(err) + case <-time.After(10 * time.Second): + t.Fatal("the query was not cancelled") + } + + // Cancel through the context. + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-started + cancel() + }() + srv.take() + _, err := s.Execute(ctx, model.ExecRequest{SQL: "SELECT SLEEP(30)", MaxRows: 10}) + check(err) + got := srv.take() + if !contains(got, "KILL QUERY 7") { + t.Errorf("commands: %q", got) + } +} + +func contains(list []string, v string) bool { + for _, x := range list { + if x == v { + return true + } + } + return false +} + +func TestConnectionErrors(t *testing.T) { + srv := newFakeServer(t, true, func(c *fakeConn, sql string) { c.fail(1064, "42000", "x") }) + srv.authError.Store(true) + _, err := Connect(context.Background(), fakeProfile(srv.port()), model.Str("wrong")) + if e := apperr.From(err); e == nil || e.Kind != apperr.Connection || e.Code != "1045 (28000)" { + t.Errorf("wrong password: %+v", e) + } + + // require needs TLS, which this server does not offer. + srv.authError.Store(false) + p := fakeProfile(srv.port()) + p.SslMode = model.SslRequire + if _, err := Connect(context.Background(), p, nil); kindOf(err) != apperr.Connection { + t.Errorf("require without TLS: %v", err) + } +} + +func TestRefusedConnectionsFailFast(t *testing.T) { + p := fakeProfile(1) + p.User, p.Database = "x", "x" + started := time.Now() + _, err := Connect(context.Background(), p, model.Str("x")) + if kindOf(err) != apperr.Connection { + t.Errorf("error %v", err) + } + if time.Since(started) > 20*time.Second { + t.Error("took too long") + } +} + +func TestLostConnection(t *testing.T) { + srv := newFakeServer(t, true, func(c *fakeConn, sql string) { + if sql == sessionSQL { + answerSession(c) + return + } + _ = c.nc.Close() + }) + s := connectFake(t, srv) + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT 1"}) + if e := apperr.From(err); e == nil || e.Kind != apperr.Connection || e.Message != closedMessage { + t.Errorf("first error: %+v", e) + } + _, err = s.ListSchemas(context.Background()) + if e := apperr.From(err); e == nil || e.Message != closedMessage { + t.Errorf("after: %+v", e) + } + if err := s.Close(); err != nil { + t.Errorf("close: %v", err) + } +} diff --git a/internal/drivers/mysql/values.go b/internal/drivers/mysql/values.go new file mode 100644 index 0000000..386d2bd --- /dev/null +++ b/internal/drivers/mysql/values.go @@ -0,0 +1,472 @@ +package mysql + +import ( + "encoding/binary" + "math" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +// Column types of the protocol. +const ( + typeDecimal = 0 + typeTiny = 1 + typeShort = 2 + typeLong = 3 + typeFloat = 4 + typeDouble = 5 + typeNull = 6 + typeTimestamp = 7 + typeLongLong = 8 + typeInt24 = 9 + typeDate = 10 + typeTime = 11 + typeDateTime = 12 + typeYear = 13 + typeNewDate = 14 + typeVarChar = 15 + typeBit = 16 + typeTimestamp2 = 17 + typeDateTime2 = 18 + typeTime2 = 19 + typeVector = 242 + typeJSON = 245 + typeNewDecimal = 246 + typeEnum = 247 + typeSet = 248 + typeTinyBlob = 249 + typeMediumBlob = 250 + typeLongBlob = 251 + typeBlob = 252 + typeVarString = 253 + typeString = 254 + typeGeometry = 255 +) + +// Column flags. +const ( + flagUnsigned = 32 + flagEnum = 256 + flagSet = 2048 +) + +const ( + binaryPreviewBytes = 32 * 1024 + maxWarnings = 100 + // Character set number of `binary` (BLOB, BINARY, VARBINARY). + binaryCharset = 63 + // ER_QUERY_INTERRUPTED. + queryInterrupted = 1317 +) + +// lossyText turns bytes into text, replacing invalid UTF-8. +func lossyText(b []byte) string { + if utf8.Valid(b) { + return string(b) + } + return strings.ToValidUTF8(string(b), "�") +} + +// formatBytes formats a text-protocol value. The server already printed +// numbers and dates (zero dates included); binary strings become 0x... and +// BIT a number. limit is the number of binary bytes shown (BinaryLimit). +func formatBytes(t byte, charset uint16, b []byte, limit int) string { + switch { + case t == typeBit && len(b) <= 8: + var n uint64 + for _, x := range b { + n = n<<8 | uint64(x) + } + return strconv.FormatUint(n, 10) + case t == typeJSON: + return lossyText(b) + case t == typeVector && len(b)%4 == 0: + items := make([]string, len(b)/4) + for i := range items { + items[i] = formatFloat32(math.Float32frombits(binary.LittleEndian.Uint32(b[i*4:]))) + } + return "[" + strings.Join(items, ",") + "]" + case t == typeGeometry || t == typeBit || t == typeVector: + return hexText(b, limit) + case isStringType(t) && charset == binaryCharset: + return hexText(b, limit) + } + return lossyText(b) +} + +// formatFloat32 writes a float the way Rust's Display does: the shortest +// text that reads back the same, never in exponent form. +func formatFloat32(f float32) string { + switch { + case math.IsInf(float64(f), 1): + return "inf" + case math.IsInf(float64(f), -1): + return "-inf" + } + return strconv.FormatFloat(float64(f), 'f', -1, 32) +} + +func isStringType(t byte) bool { + switch t { + case typeVarChar, typeVarString, typeString, typeTinyBlob, typeMediumBlob, typeLongBlob, typeBlob: + return true + } + return false +} + +// hexText is 0x + uppercase hexadecimal, the way the mysql client shows +// binary data, cut to limit bytes. +func hexText(b []byte, limit int) string { + shown := b[:min(len(b), limit)] + const digits = "0123456789ABCDEF" + var sb strings.Builder + sb.Grow(2 + len(shown)*2) + sb.WriteString("0x") + for _, x := range shown { + sb.WriteByte(digits[x>>4]) + sb.WriteByte(digits[x&0x0f]) + } + if len(b) > len(shown) { + sb.WriteString("… (" + strconv.Itoa(len(b)) + " bytes)") + } + return sb.String() +} + +func valueKind(t byte, charset uint16) model.ValueKind { + switch t { + case typeTiny, typeShort, typeInt24, typeLong, typeLongLong, typeDecimal, typeNewDecimal, + typeFloat, typeDouble, typeBit: + return model.KindNumber + case typeDate, typeNewDate, typeTime, typeTime2, typeDateTime, typeDateTime2, typeTimestamp, + typeTimestamp2, typeYear: + return model.KindTemporal + case typeJSON: + return model.KindJSON + case typeGeometry: + return model.KindBinary + } + if isStringType(t) && charset == binaryCharset { + return model.KindBinary + } + if isStringType(t) || t == typeEnum || t == typeSet { + return model.KindText + } + return model.KindOther +} + +// typeName is the type from the result metadata (INT UNSIGNED, VARBINARY...). +func typeName(t byte, flags uint16, charset uint16) string { + binary := charset == binaryCharset + var name string + switch t { + case typeDecimal, typeNewDecimal: + name = "DECIMAL" + case typeTiny: + name = "TINYINT" + case typeShort: + name = "SMALLINT" + case typeInt24: + name = "MEDIUMINT" + case typeLong: + name = "INT" + case typeLongLong: + name = "BIGINT" + case typeFloat: + name = "FLOAT" + case typeDouble: + name = "DOUBLE" + case typeNull: + name = "NULL" + case typeTimestamp, typeTimestamp2: + name = "TIMESTAMP" + case typeDate, typeNewDate: + name = "DATE" + case typeTime, typeTime2: + name = "TIME" + case typeDateTime, typeDateTime2: + name = "DATETIME" + case typeYear: + name = "YEAR" + case typeBit: + name = "BIT" + case typeJSON: + name = "JSON" + case typeVector: + name = "VECTOR" + case typeGeometry: + name = "GEOMETRY" + case typeEnum: + name = "ENUM" + case typeSet: + name = "SET" + case typeString: + switch { + case flags&flagEnum != 0: + name = "ENUM" + case flags&flagSet != 0: + name = "SET" + case binary: + name = "BINARY" + default: + name = "CHAR" + } + case typeVarChar, typeVarString: + if binary { + name = "VARBINARY" + } else { + name = "VARCHAR" + } + case typeTinyBlob, typeMediumBlob, typeLongBlob, typeBlob: + if binary { + name = "BLOB" + } else { + name = "TEXT" + } + default: + name = "UNKNOWN" + } + numeric := valueKind(t, charset) == model.KindNumber && t != typeBit + if numeric && flags&flagUnsigned != 0 { + return name + " UNSIGNED" + } + return name +} + +func columnInfos(cols []column) []model.ColumnInfo { + out := make([]model.ColumnInfo, len(cols)) + for i, c := range cols { + out[i] = model.ColumnInfo{ + Name: c.name, + TypeName: typeName(c.typ, c.flags, c.charset), + Kind: valueKind(c.typ, c.charset), + } + } + return out +} + +func formatRow(cols []column, values [][]byte, limit int) model.Row { + row := make(model.Row, len(cols)) + for i, c := range cols { + if i < len(values) && values[i] != nil { + v := formatBytes(c.typ, c.charset, values[i], limit) + row[i] = &v + } + } + return row +} + +// productVersion is "MySQL 8.4.2" or "MariaDB 11.4.2", from VERSION(). +func productVersion(version string) string { + v := strings.TrimSpace(version) + mariadb := strings.Contains(strings.ToLower(v), "mariadb") + // Old MariaDB servers prefix the version with 5.5.5- for compatibility. + if mariadb { + v = strings.TrimPrefix(v, "5.5.5-") + } + number, _, _ := strings.Cut(v, "-") + if mariadb { + return "MariaDB " + number + } + return "MySQL " + number +} + +// defaultExpr is COLUMN_DEFAULT as an SQL expression. MariaDB already +// writes literals quoted (and a NULL default as NULL); MySQL writes the bare +// value and marks expressions with DEFAULT_GENERATED. +func defaultExpr(value, extra string, mariadb bool) *string { + if mariadb { + if strings.EqualFold(value, "NULL") { + return nil + } + return &value + } + if strings.Contains(strings.ToUpper(extra), "DEFAULT_GENERATED") { + lower := strings.ToLower(value) + for _, p := range []string{"current_timestamp", "now(", "localtime", "current_date"} { + if strings.HasPrefix(lower, p) { + return &value + } + } + e := "(" + value + ")" + return &e + } + if strings.HasPrefix(value, "b'") { + return &value + } + e := "'" + strings.ReplaceAll(strings.ReplaceAll(value, `\`, `\\`), "'", "''") + "'" + return &e +} + +func isSystemSchema(name string) bool { + switch strings.ToLower(name) { + case "mysql", "information_schema", "performance_schema", "sys": + return true + } + return false +} + +// prepareSQL drops the trailing ; (the interface may keep it) and spaces. +func prepareSQL(sql string) string { + text := strings.TrimRightFunc(sql, isSpace) + for strings.HasSuffix(text, ";") { + text = strings.TrimRightFunc(text[:len(text)-1], isSpace) + } + return text +} + +// isSpace is Unicode White_Space, as Rust's trim. +func isSpace(r rune) bool { return unicode.IsSpace(r) } + +func firstKeyword(sql string) string { + if kw := drivers.FirstKeywords(sql, 1); len(kw) > 0 { + return kw[0] + } + return "" +} + +// isSelectLike says whether sql_select_limit applies to the statement's +// top-level SELECT. +func isSelectLike(sql string) bool { + switch firstKeyword(sql) { + case "SELECT", "WITH", "TABLE", "VALUES": + return true + case "": + return strings.HasPrefix(skipComments(sql), "(") + } + return false +} + +func skipComments(sql string) string { + s := strings.TrimLeftFunc(sql, isSpace) + for { + switch { + case strings.HasPrefix(s, "--") || strings.HasPrefix(s, "#"): + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = strings.TrimLeftFunc(s[i+1:], isSpace) + } else { + s = "" + } + case strings.HasPrefix(s, "/*"): + if i := strings.Index(s[2:], "*/"); i >= 0 { + s = strings.TrimLeftFunc(s[2+i+2:], isSpace) + } else { + s = "" + } + default: + return s + } + } +} + +// isDDL says whether the statement changes the structure the editing cache +// describes. +func isDDL(sql string) bool { + switch firstKeyword(sql) { + case "CREATE", "ALTER", "DROP", "RENAME": + return true + } + return false +} + +// errorPosition is the position (0-based, in characters) of a syntax error, +// from MySQL's "... near '' at line N". The quoted +// text is the statement from the error on, cut at 80 characters. +func errorPosition(sql, message string) *int { + const near, atLine = " near '", "' at line " + start := strings.Index(message, near) + end := strings.LastIndex(message, atLine) + if start < 0 || end < 0 { + return nil + } + start += len(near) + if end < start { + return nil + } + snippet := message[start:end] + digits := message[end+len(atLine):] + n := 0 + for n < len(digits) && digits[n] >= '0' && digits[n] <= '9' { + n++ + } + line, err := strconv.Atoi(digits[:n]) + if err != nil { + return nil + } + var b int + switch { + case snippet == "": + // The statement ended too early. + b = len(strings.TrimRightFunc(sql, isSpace)) + case strings.HasSuffix(sql, snippet): + b = len(sql) - len(snippet) + default: + lineStart := 0 + for i := 1; i < line; i++ { + nl := strings.IndexByte(sql[lineStart:], '\n') + if nl < 0 { + return nil + } + lineStart += nl + 1 + } + at := strings.Index(sql[lineStart:], snippet) + if at < 0 { + return nil + } + b = lineStart + at + } + p := utf8.RuneCountInString(sql[:b]) + return &p +} + +// stringLiteral is a string literal that reads the same whatever sql_mode +// says about backslashes: hexadecimal with a character set introducer. +func stringLiteral(s string) string { + const digits = "0123456789ABCDEF" + var sb strings.Builder + sb.Grow(12 + len(s)*2) + sb.WriteString("_utf8mb4 X'") + for i := 0; i < len(s); i++ { + sb.WriteByte(digits[s[i]>>4]) + sb.WriteByte(digits[s[i]&0x0f]) + } + sb.WriteByte('\'') + return sb.String() +} + +// bindLiterals replaces each ? outside quotes and backticks with the +// string literal of the next value. Metadata queries use it. +func bindLiterals(sql string, values ...string) string { + var sb strings.Builder + next := 0 + for i := 0; i < len(sql); i++ { + c := sql[i] + switch c { + case '\'', '"', '`': + j := i + 1 + for j < len(sql) && sql[j] != c { + if sql[j] == '\\' && c != '`' { + j++ + } + j++ + } + j = min(j, len(sql)-1) + sb.WriteString(sql[i : j+1]) + i = j + case '?': + if next < len(values) { + sb.WriteString(stringLiteral(values[next])) + next++ + } else { + sb.WriteByte(c) + } + default: + sb.WriteByte(c) + } + } + return sb.String() +} diff --git a/internal/drivers/mysql/values_test.go b/internal/drivers/mysql/values_test.go new file mode 100644 index 0000000..0e84cbc --- /dev/null +++ b/internal/drivers/mysql/values_test.go @@ -0,0 +1,235 @@ +package mysql + +import ( + "encoding/binary" + "math" + "strconv" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func strOrNil(p *string) string { + if p == nil { + return "" + } + return *p +} + +func TestColumnDefaultsBecomeSQL(t *testing.T) { + cases := []struct { + value, extra string + mariadb bool + want string + }{ + // MySQL: bare values, expressions marked DEFAULT_GENERATED. + {"it's", "", false, "'it''s'"}, + {`a\b`, "", false, `'a\\b'`}, + {"0", "", false, "'0'"}, + {"b'1'", "", false, "b'1'"}, + {"CURRENT_TIMESTAMP", "DEFAULT_GENERATED", false, "CURRENT_TIMESTAMP"}, + {"uuid()", "DEFAULT_GENERATED", false, "(uuid())"}, + // MariaDB: already SQL, with NULL spelled out. + {"'x'", "", true, "'x'"}, + {"NULL", "", true, ""}, + } + for _, c := range cases { + if got := strOrNil(defaultExpr(c.value, c.extra, c.mariadb)); got != c.want { + t.Errorf("defaultExpr(%q, %q, %v) = %s, want %s", c.value, c.extra, c.mariadb, got, c.want) + } + } +} + +func TestFindsSyntaxErrorPosition(t *testing.T) { + msg := func(near string, line int) string { + return "You have an error in your SQL syntax; check the manual that corresponds to your " + + "MySQL server version for the right syntax to use near '" + near + "' at line " + strconv.Itoa(line) + } + pos := func(p *int) int { + if p == nil { + return -1 + } + return *p + } + cases := []struct { + sql, message string + want int + }{ + {"SELECT *\nFROMM lq_x", msg("FROMM lq_x", 2), 9}, + // Cut snippet: located from the reported line on. + {"select 1 x,\n 2 y fromm t where a = 'é' and b = 1", msg("fromm t where", 2), 18}, + {"select 1 +", msg("", 1), 10}, + // Earlier text on the same line equal to a short suffix. + {"select 'é', 1 1", msg("1", 1), 14}, + {"select 'é', 1 1", "Unknown column 'x' in 'field list'", -1}, + // Quotes inside the snippet. + {"selec 'a' from t", msg("selec 'a' from t", 1), 0}, + } + for _, c := range cases { + if got := pos(errorPosition(c.sql, c.message)); got != c.want { + t.Errorf("errorPosition(%q) = %d, want %d", c.sql, got, c.want) + } + } +} + +func TestFormatsValues(t *testing.T) { + limit := binaryPreviewBytes + cases := []struct { + typ byte + charset uint16 + value []byte + want string + }{ + {typeBlob, 63, []byte{0, 0xff, 0x10}, "0x00FF10"}, + {typeVarString, 63, []byte{0xca, 0xfe}, "0xCAFE"}, + {typeVarString, 255, []byte("ação"), "ação"}, + {typeBlob, 255, []byte("text"), "text"}, + {typeBit, 63, []byte{0x15}, "21"}, + {typeBit, 63, []byte{1, 0}, "256"}, + {typeJSON, 63, []byte(`{"a": 1}`), `{"a": 1}`}, + {typeNewDecimal, 63, []byte("12345678901234567890.123456789"), "12345678901234567890.123456789"}, + {typeDateTime, 63, []byte("0000-00-00 00:00:00"), "0000-00-00 00:00:00"}, + {typeGeometry, 63, []byte{1, 2}, "0x0102"}, + {typeVarString, 33, []byte{0xff, 'a'}, "�a"}, + } + for _, c := range cases { + if got := formatBytes(c.typ, c.charset, c.value, limit); got != c.want { + t.Errorf("formatBytes(%d, %d, %v) = %q, want %q", c.typ, c.charset, c.value, got, c.want) + } + } + var v []byte + for _, f := range []float32{1.5, -2} { + v = binary.LittleEndian.AppendUint32(v, math.Float32bits(f)) + } + if got := formatBytes(typeVector, 63, v, limit); got != "[1.5,-2]" { + t.Errorf("vector: %q", got) + } + big := make([]byte, binaryPreviewBytes+1) + if got := formatBytes(typeBlob, 63, big, limit); !strings.HasSuffix(got, + "… ("+strconv.Itoa(binaryPreviewBytes+1)+" bytes)") { + t.Errorf("preview: ...%q", got[len(got)-30:]) + } + if got := formatBytes(typeBlob, 63, big, math.MaxInt); len(got) != 2+2*len(big) { + t.Errorf("full value: %d characters", len(got)) + } +} + +func TestNamesAndKinds(t *testing.T) { + names := []struct { + typ byte + flags uint16 + charset uint16 + want string + }{ + {typeLongLong, flagUnsigned, 63, "BIGINT UNSIGNED"}, + {typeVarString, 0, 63, "VARBINARY"}, + {typeVarString, 0, 255, "VARCHAR"}, + {typeBlob, 0, 63, "BLOB"}, + {typeBlob, 0, 45, "TEXT"}, + {typeString, flagEnum, 45, "ENUM"}, + {typeBit, flagUnsigned, 63, "BIT"}, + {typeNewDecimal, 0, 63, "DECIMAL"}, + } + for _, c := range names { + if got := typeName(c.typ, c.flags, c.charset); got != c.want { + t.Errorf("typeName(%d, %d, %d) = %q, want %q", c.typ, c.flags, c.charset, got, c.want) + } + } + kinds := []struct { + typ byte + charset uint16 + want model.ValueKind + }{ + {typeNewDecimal, 63, model.KindNumber}, + {typeDateTime, 63, model.KindTemporal}, + {typeJSON, 63, model.KindJSON}, + {typeBlob, 63, model.KindBinary}, + {typeBlob, 255, model.KindText}, + {typeEnum, 33, model.KindText}, + {typeNull, 63, model.KindOther}, + } + for _, c := range kinds { + if got := valueKind(c.typ, c.charset); got != c.want { + t.Errorf("valueKind(%d, %d) = %q, want %q", c.typ, c.charset, got, c.want) + } + } +} + +func TestVersionsAndStatementKinds(t *testing.T) { + versions := map[string]string{ + "8.4.2": "MySQL 8.4.2", + "8.0.36-0ubuntu0.22.04.1": "MySQL 8.0.36", + "11.4.2-MariaDB-ubu2404": "MariaDB 11.4.2", + "5.5.5-10.6.12-MariaDB": "MariaDB 10.6.12", + } + for in, want := range versions { + if got := productVersion(in); got != want { + t.Errorf("productVersion(%q) = %q, want %q", in, got, want) + } + } + for sql, want := range map[string]bool{ + " select 1": true, + "WITH x AS (SELECT 1) SELECT * FROM x": true, + "-- c\n# d\n/* e */ (SELECT 1) UNION (SELECT 2)": true, + "UPDATE t SET a = 1": false, + "CALL p()": false, + } { + if got := isSelectLike(sql); got != want { + t.Errorf("isSelectLike(%q) = %v", sql, got) + } + } + if got := prepareSQL("select 1 ;\n "); got != "select 1" { + t.Errorf("prepareSQL: %q", got) + } +} + +func TestSpotsSetOperationsAndDDL(t *testing.T) { + for sql, want := range map[string]bool{ + "select a from t union select a from u": true, + "(SELECT 1)\nINTERSECT\n(SELECT 2)": true, + "select 'union', \"except\", `intersect` from t": false, + "select 'it\\'s union' from t": false, + "select a -- union\n, b # except\n /* intersect */ from reunion": false, + // 1--1 is arithmetic, not a comment. + "select 1--1\nunion select 2": true, + } { + if got := hasSetOperation(sql); got != want { + t.Errorf("hasSetOperation(%q) = %v", sql, got) + } + } + for sql, want := range map[string]bool{ + "select * from t": true, + "values row(1)": false, + "show tables": false, + "select 1 union select 2": false, + } { + if got := mayBeEditable(sql); got != want { + t.Errorf("mayBeEditable(%q) = %v", sql, got) + } + } + if !isDDL("alter table t add primary key (id)") || isDDL("select 1") { + t.Error("isDDL") + } +} + +func TestCatalogQueryUsesHexLiterals(t *testing.T) { + if got := stringLiteral("a'b\\"); got != "_utf8mb4 X'6127625C'" { + t.Errorf("stringLiteral: %s", got) + } + if got := stringLiteral(""); got != "_utf8mb4 X''" { + t.Errorf("stringLiteral empty: %s", got) + } + sql := catalogSQL("db", "t") + if n := strings.Count(sql, "TABLE_SCHEMA = _utf8mb4 X'6462'"); n != 3 { + t.Errorf("schema filter %d times", n) + } + if n := strings.Count(sql, ";"); n != 2 { + t.Errorf("%d semicolons", n) + } + got := bindLiterals("SELECT '?', `a?`, \"?\\\"?\" FROM t WHERE a = ? AND b = ? AND c = ?", "x", "y") + want := "SELECT '?', `a?`, \"?\\\"?\" FROM t WHERE a = _utf8mb4 X'78' AND b = _utf8mb4 X'79' AND c = ?" + if got != want { + t.Errorf("bindLiterals:\n got %s\nwant %s", got, want) + } +} diff --git a/internal/drivers/mysql/wire.go b/internal/drivers/mysql/wire.go new file mode 100644 index 0000000..e2761ef --- /dev/null +++ b/internal/drivers/mysql/wire.go @@ -0,0 +1,904 @@ +package mysql + +// The command phase of the MySQL client/server protocol. +// +// go-sql-driver opens the connection: it dials, negotiates TLS and runs the +// authentication plugins. Its own command code then throws away what this +// driver needs: the origin of each result column (schema, original table +// and column), the server status flags, warning counts and the info text of +// OK packets. So once the handshake is done, the session takes over the +// driver's network connection and speaks the command phase itself; the +// driver only sends COM_QUIT when the session closes. + +import ( + "bufio" + "database/sql/driver" + "encoding/binary" + "errors" + "io" + "math" + "net" + "reflect" + "strconv" + "sync/atomic" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +const ( + comQuery = 0x03 + comStmtPrepare = 0x16 + comStmtExecute = 0x17 + comStmtClose = 0x19 + + pktOK = 0x00 + pktEOF = 0xfe + pktERR = 0xff + pktLocalInFile = 0xfb + + statusInTrans = 0x0001 + statusAutocommit = 0x0002 + statusMoreResults = 0x0008 + + // CLIENT_DEPRECATE_EOF: result sets end with an OK packet, not EOF. + capDeprecateEOF = 1 << 24 + // MARIADB_CLIENT_CACHE_METADATA (extended capability). + extCacheMetadata = 1 << 4 + + // Largest payload of one packet; longer payloads span several. + maxPayload = 1<<24 - 1 +) + +// errClosed reports a connection lost in the middle of a command. +var errClosed = errors.New("connection closed") + +// errMalformed reports a packet this client cannot read; the connection is +// out of step with the server afterwards. +var errMalformed = errors.New("malformed packet") + +// serverError is an ERR packet. +type serverError struct { + code uint16 + state string + message string +} + +func (e *serverError) Error() string { + return strconv.Itoa(int(e.code)) + " (" + e.state + "): " + e.message +} + +// column is a column definition of a result set. +type column struct { + schema string + table string // alias in the query + orgTable string + name string // alias in the query + orgName string + charset uint16 + length uint32 + typ byte + flags uint16 + decimals byte +} + +// okPacket is an OK packet, or the EOF packet that ends a result set. +type okPacket struct { + affected uint64 + insertID uint64 + status uint16 + warnings uint16 + info string +} + +// wire is one connection in the command phase. +type wire struct { + nc net.Conn + r *bufio.Reader + seq byte + + deprecateEOF bool + cacheMetadata bool + + broken atomic.Bool + // Status flags of the last OK or EOF packet of the current command; + // hasStatus is false until one arrives (after an error there is none). + status uint16 + hasStatus bool +} + +// takeOver returns the command-phase connection of a connection that +// go-sql-driver has just opened. It reads the driver's private fields; the +// layout is checked so a driver upgrade fails here and not on the wire. +func takeOver(dc driver.Conn) (*wire, error) { + fail := func(what string) (*wire, error) { + return nil, apperr.Internalf("Unsupported MySQL driver version (%s).", what) + } + v := reflect.ValueOf(dc) + if v.Kind() != reflect.Pointer || v.IsNil() || v.Elem().Kind() != reflect.Struct { + return fail("connection type") + } + e := v.Elem() + field := func(name string, kind reflect.Kind) (reflect.Value, bool) { + f := e.FieldByName(name) + return f, f.IsValid() && f.Kind() == kind + } + nc, ok := field("netConn", reflect.Interface) + if !ok || nc.IsNil() { + return fail("netConn") + } + caps, ok := field("capabilities", reflect.Uint32) + if !ok { + return fail("capabilities") + } + ext, ok := field("extCapabilities", reflect.Uint32) + if !ok { + return fail("extCapabilities") + } + compress, ok := field("compress", reflect.Bool) + if !ok { + return fail("compress") + } + if compress.Bool() { + return fail("compression is on") + } + buf, ok := field("buf", reflect.Struct) + if !ok { + return fail("buf") + } + if pending := buf.FieldByName("buf"); !pending.IsValid() || pending.Kind() != reflect.Slice { + return fail("buf.buf") + } else if pending.Len() > 0 { + return fail("unread data after the handshake") + } + // Unexported fields cannot be read through Interface; this reads the + // interface value in place. + conn, ok := reflect.NewAt(nc.Type(), nc.Addr().UnsafePointer()).Elem().Interface().(net.Conn) + if !ok || conn == nil { + return fail("netConn type") + } + return &wire{ + nc: conn, + r: bufio.NewReaderSize(conn, 16*1024), + deprecateEOF: caps.Uint()&capDeprecateEOF != 0, + cacheMetadata: ext.Uint()&extCacheMetadata != 0, + }, nil +} + +func (w *wire) isBroken() bool { return w.broken.Load() } + +// fail marks the connection unusable after a network or protocol error. +func (w *wire) fail(err error) error { + w.broken.Store(true) + if errors.Is(err, errMalformed) { + return err + } + return errClosed +} + +// cut makes a blocked read or write fail now; the connection is lost. +func (w *wire) cut() { + _ = w.nc.SetDeadline(time.Now()) +} + +func (w *wire) readPacket() ([]byte, error) { + var payload []byte + for { + var hdr [4]byte + if _, err := io.ReadFull(w.r, hdr[:]); err != nil { + return nil, w.fail(err) + } + n := int(hdr[0]) | int(hdr[1])<<8 | int(hdr[2])<<16 + w.seq = hdr[3] + 1 + chunk := make([]byte, n) + if _, err := io.ReadFull(w.r, chunk); err != nil { + return nil, w.fail(err) + } + if payload == nil && n < maxPayload { + return chunk, nil + } + payload = append(payload, chunk...) + if n < maxPayload { + return payload, nil + } + } +} + +// writePacket sends a payload, split into packets of at most maxPayload +// bytes (a payload of exactly that size is followed by an empty packet). +func (w *wire) writePacket(payload []byte) error { + for { + n := min(len(payload), maxPayload) + out := make([]byte, 4+n) + out[0], out[1], out[2], out[3] = byte(n), byte(n>>8), byte(n>>16), w.seq + copy(out[4:], payload[:n]) + w.seq++ + if _, err := w.nc.Write(out); err != nil { + return w.fail(err) + } + payload = payload[n:] + if n < maxPayload { + return nil + } + } +} + +// command starts a command: the payload's first byte is the command. +func (w *wire) command(payload []byte) error { + if w.isBroken() { + return errClosed + } + w.seq = 0 + return w.writePacket(payload) +} + +// query sends COM_QUERY; the results are read through the response. +func (w *wire) query(sql string) (*response, error) { + payload := make([]byte, 1+len(sql)) + payload[0] = comQuery + copy(payload[1:], sql) + w.hasStatus = false + if err := w.command(payload); err != nil { + return nil, err + } + return &response{w: w}, nil +} + +// exec runs statements and returns the last OK packet. +func (w *wire) exec(sql string) (okPacket, error) { + resp, err := w.query(sql) + if err != nil { + return okPacket{}, err + } + err = resp.drain() + return resp.ok, err +} + +// textRows runs statements and returns the rows of each result set that +// has columns, every value as text (nil is NULL). +func (w *wire) textRows(sql string) ([][][]*string, error) { + resp, err := w.query(sql) + if err != nil { + return nil, err + } + return resp.collect() +} + +// preparedStmt is a statement prepared with COM_STMT_PREPARE. +type preparedStmt struct { + id uint32 + params int + columns []column +} + +func (w *wire) prepare(sql string) (*preparedStmt, error) { + payload := make([]byte, 1+len(sql)) + payload[0] = comStmtPrepare + copy(payload[1:], sql) + if err := w.command(payload); err != nil { + return nil, err + } + data, err := w.readPacket() + if err != nil { + return nil, err + } + if len(data) > 0 && data[0] == pktERR { + return nil, parseErr(data) + } + if len(data) < 9 || data[0] != pktOK { + return nil, w.fail(errMalformed) + } + st := &preparedStmt{ + id: binary.LittleEndian.Uint32(data[1:5]), + params: int(binary.LittleEndian.Uint16(data[7:9])), + } + columns := int(binary.LittleEndian.Uint16(data[5:7])) + if st.params > 0 { + if _, err := w.readColumns(st.params); err != nil { + return nil, err + } + } + if columns > 0 { + if st.columns, err = w.readColumns(columns); err != nil { + return nil, err + } + } + return st, nil +} + +// readColumns reads n column definitions and the EOF packet after them +// when the server still sends one. +func (w *wire) readColumns(n int) ([]column, error) { + cols := make([]column, n) + for i := range cols { + data, err := w.readPacket() + if err != nil { + return nil, err + } + c, ok := parseColumn(data) + if !ok { + return nil, w.fail(errMalformed) + } + cols[i] = c + } + if err := w.skipEOF(); err != nil { + return nil, err + } + return cols, nil +} + +func (w *wire) skipEOF() error { + if w.deprecateEOF { + return nil + } + _, err := w.readPacket() + return err +} + +// paramKind is the type a statement parameter is sent as. +type paramKind int + +const ( + paramNull paramKind = iota + // Text the server converts to the column type. + paramText + // BIGINT UNSIGNED. + paramUint +) + +type param struct { + kind paramKind + text string + num uint64 +} + +func textParam(s string) param { return param{kind: paramText, text: s} } +func uintParam(n uint64) param { return param{kind: paramUint, num: n} } +func (p param) String() string { // for test failure messages + switch p.kind { + case paramText: + return strconv.Quote(p.text) + case paramUint: + return strconv.FormatUint(p.num, 10) + } + return "NULL" +} + +// execute runs a prepared statement with COM_STMT_EXECUTE; rows arrive in +// the binary protocol. +func (w *wire) execute(st *preparedStmt, params []param) (*response, error) { + if len(params) != st.params { + return nil, apperr.Internalf("The statement has %d parameters, %d given.", st.params, len(params)) + } + payload := []byte{comStmtExecute, 0, 0, 0, 0, 0, 1, 0, 0, 0} + binary.LittleEndian.PutUint32(payload[1:5], st.id) + if n := len(params); n > 0 { + nulls := make([]byte, (n+7)/8) + for i, p := range params { + if p.kind == paramNull { + nulls[i/8] |= 1 << (i % 8) + } + } + payload = append(payload, nulls...) + payload = append(payload, 1) // new parameters bound + for _, p := range params { + switch p.kind { + case paramText: + payload = append(payload, typeVarString, 0) + case paramUint: + payload = append(payload, typeLongLong, 0x80) + default: + payload = append(payload, typeNull, 0) + } + } + for _, p := range params { + switch p.kind { + case paramText: + payload = appendLenenc(payload, uint64(len(p.text))) + payload = append(payload, p.text...) + case paramUint: + payload = binary.LittleEndian.AppendUint64(payload, p.num) + } + } + } + w.hasStatus = false + if err := w.command(payload); err != nil { + return nil, err + } + return &response{w: w, binary: true, stmtColumns: st.columns}, nil +} + +// closeStmt frees a prepared statement; the server sends no answer. +func (w *wire) closeStmt(st *preparedStmt) { + payload := []byte{comStmtClose, 0, 0, 0, 0} + binary.LittleEndian.PutUint32(payload[1:], st.id) + _ = w.command(payload) +} + +// runPrepared prepares, executes and frees a statement. It returns the last +// OK packet and the rows of the result sets, as text. +func (w *wire) runPrepared(sql string, params []param) (okPacket, [][][]*string, error) { + st, err := w.prepare(sql) + if err != nil { + return okPacket{}, nil, err + } + defer w.closeStmt(st) + resp, err := w.execute(st, params) + if err != nil { + return okPacket{}, nil, err + } + sets, err := resp.collect() + return resp.ok, sets, err +} + +// response reads the results of one command: result sets with columns and +// rows, and OK packets of statements without rows. +type response struct { + w *wire + binary bool + // Columns of the prepared statement, for results whose metadata the + // server leaves out (MariaDB metadata cache). + stmtColumns []column + + // Columns of the current result; nil for an OK packet. + columns []column + // The OK packet of the current result, or the packet that ended its rows. + ok okPacket + + started bool + inRows bool + more bool + finished bool + // The server asked for a local file (LOAD DATA LOCAL INFILE); it was + // refused with an empty file. + localInfile bool +} + +// setEnd records the packet that ends a result. +func (r *response) setEnd(ok okPacket) { + r.ok = ok + r.more = ok.status&statusMoreResults != 0 + r.w.status = ok.status + r.w.hasStatus = true +} + +// next moves to the next result, skipping the rest of the current one. It +// returns false when there are no more. +func (r *response) next() (bool, error) { + if r.finished { + return false, nil + } + for r.inRows { + if _, err := r.row(); err != nil { + return false, err + } + } + if r.started && !r.more { + r.finished = true + return false, nil + } + r.started = true + for { + data, err := r.w.readPacket() + if err != nil { + r.finished = true + return false, err + } + if len(data) == 0 { + r.finished = true + return false, r.w.fail(errMalformed) + } + switch data[0] { + case pktOK: + ok, valid := parseOK(data) + if !valid { + r.finished = true + return false, r.w.fail(errMalformed) + } + r.columns = nil + r.setEnd(ok) + return true, nil + case pktERR: + r.finished = true + return false, parseErr(data) + case pktLocalInFile: + r.localInfile = true + if err := r.w.writePacket(nil); err != nil { + r.finished = true + return false, err + } + continue + } + count, _, n := readLenenc(data) + if n == 0 || count == 0 || count > math.MaxUint16 { + r.finished = true + return false, r.w.fail(errMalformed) + } + follows := true + if r.w.cacheMetadata { + if n >= len(data) { + r.finished = true + return false, r.w.fail(errMalformed) + } + follows = data[n] == 1 + } + if follows { + cols, err := r.w.readColumns(int(count)) + if err != nil { + r.finished = true + return false, err + } + r.columns = cols + } else { + if len(r.stmtColumns) != int(count) { + r.finished = true + return false, r.w.fail(errMalformed) + } + if err := r.w.skipEOF(); err != nil { + r.finished = true + return false, err + } + r.columns = r.stmtColumns + } + r.inRows = true + return true, nil + } +} + +// row returns the next row of the current result set, nil at its end. +// Values are the bytes the server sent (text protocol) or their text form +// (binary protocol); nil is NULL. +func (r *response) row() ([][]byte, error) { + if !r.inRows { + return nil, nil + } + data, err := r.w.readPacket() + if err != nil { + r.inRows, r.finished = false, true + return nil, err + } + if len(data) == 0 { + r.inRows, r.finished = false, true + return nil, r.w.fail(errMalformed) + } + switch { + case data[0] == pktERR: + r.inRows, r.finished = false, true + return nil, parseErr(data) + case data[0] == pktEOF && len(data) < maxPayload && (r.w.deprecateEOF || len(data) < 9): + r.inRows = false + var ok okPacket + var valid bool + if r.w.deprecateEOF { + ok, valid = parseOK(data) + } else { + ok, valid = parseEOF(data) + } + if !valid { + r.finished = true + return nil, r.w.fail(errMalformed) + } + r.setEnd(ok) + return nil, nil + } + var values [][]byte + var valid bool + if r.binary { + values, valid = parseBinaryRow(data, r.columns) + } else { + values, valid = parseTextRow(data, len(r.columns)) + } + if !valid { + r.inRows, r.finished = false, true + return nil, r.w.fail(errMalformed) + } + return values, nil +} + +// drain reads what is left of the response and returns its first error. +func (r *response) drain() error { + for { + more, err := r.next() + if err != nil || !more { + return err + } + } +} + +// collect reads every result set with columns, values as text. +func (r *response) collect() ([][][]*string, error) { + var sets [][][]*string + for { + more, err := r.next() + if err != nil { + return nil, err + } + if !more { + return sets, nil + } + if r.columns == nil { + continue + } + rows := [][]*string{} + for { + values, err := r.row() + if err != nil { + return nil, err + } + if values == nil { + break + } + row := make([]*string, len(values)) + for i, v := range values { + if v != nil { + t := lossyText(v) + row[i] = &t + } + } + rows = append(rows, row) + } + sets = append(sets, rows) + } +} + +// readLenenc reads a length-encoded integer. n is the number of bytes +// read, 0 when malformed; null is the NULL marker of text rows. +func readLenenc(b []byte) (v uint64, null bool, n int) { + if len(b) == 0 { + return 0, false, 0 + } + switch b[0] { + case 0xfb: + return 0, true, 1 + case 0xfc: + if len(b) < 3 { + return 0, false, 0 + } + return uint64(binary.LittleEndian.Uint16(b[1:3])), false, 3 + case 0xfd: + if len(b) < 4 { + return 0, false, 0 + } + return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 + case 0xfe: + if len(b) < 9 { + return 0, false, 0 + } + return binary.LittleEndian.Uint64(b[1:9]), false, 9 + case 0xff: + return 0, false, 0 + } + return uint64(b[0]), false, 1 +} + +func appendLenenc(b []byte, v uint64) []byte { + switch { + case v < 0xfb: + return append(b, byte(v)) + case v <= 0xffff: + return append(b, 0xfc, byte(v), byte(v>>8)) + case v <= 0xffffff: + return append(b, 0xfd, byte(v), byte(v>>8), byte(v>>16)) + } + b = append(b, 0xfe) + return binary.LittleEndian.AppendUint64(b, v) +} + +// readLenencBytes reads a length-encoded string; n is 0 when malformed. +func readLenencBytes(b []byte) (s []byte, null bool, n int) { + l, null, m := readLenenc(b) + if m == 0 || null { + return nil, null, m + } + if uint64(len(b)-m) < l { + return nil, false, 0 + } + end := m + int(l) + return b[m:end:end], false, end +} + +func parseColumn(data []byte) (column, bool) { + var c column + pos := 0 + text := func() (string, bool) { + s, _, n := readLenencBytes(data[pos:]) + if n == 0 { + return "", false + } + pos += n + return string(s), true + } + var ok bool + if _, ok = text(); !ok { // catalog + return c, false + } + if c.schema, ok = text(); !ok { + return c, false + } + if c.table, ok = text(); !ok { + return c, false + } + if c.orgTable, ok = text(); !ok { + return c, false + } + if c.name, ok = text(); !ok { + return c, false + } + if c.orgName, ok = text(); !ok { + return c, false + } + // Length of the fixed fields (0x0c), then charset, length, type, flags + // and decimals. + _, _, n := readLenenc(data[pos:]) + if n == 0 || len(data) < pos+n+10 { + return c, false + } + pos += n + c.charset = binary.LittleEndian.Uint16(data[pos:]) + c.length = binary.LittleEndian.Uint32(data[pos+2:]) + c.typ = data[pos+6] + c.flags = binary.LittleEndian.Uint16(data[pos+7:]) + c.decimals = data[pos+9] + return c, true +} + +// parseOK reads an OK packet (header 0x00, or 0xfe when it ends rows). +func parseOK(data []byte) (okPacket, bool) { + var ok okPacket + pos := 1 + var n int + if ok.affected, _, n = readLenenc(data[pos:]); n == 0 { + return ok, false + } + pos += n + if ok.insertID, _, n = readLenenc(data[pos:]); n == 0 { + return ok, false + } + pos += n + if len(data) < pos+4 { + // Old servers may leave the status out of the last OK. + return ok, len(data) == pos + } + ok.status = binary.LittleEndian.Uint16(data[pos:]) + ok.warnings = binary.LittleEndian.Uint16(data[pos+2:]) + ok.info = string(data[pos+4:]) + return ok, true +} + +// parseEOF reads an EOF packet: warnings, then status flags. +func parseEOF(data []byte) (okPacket, bool) { + var ok okPacket + if len(data) >= 5 { + ok.warnings = binary.LittleEndian.Uint16(data[1:]) + ok.status = binary.LittleEndian.Uint16(data[3:]) + } + return ok, true +} + +func parseErr(data []byte) error { + e := &serverError{} + if len(data) >= 3 { + e.code = binary.LittleEndian.Uint16(data[1:3]) + } + pos := 3 + if len(data) >= 9 && data[3] == '#' { + e.state = string(data[4:9]) + pos = 9 + } + if pos < len(data) { + e.message = string(data[pos:]) + } + return e +} + +// parseTextRow reads a text-protocol row of n values. +func parseTextRow(data []byte, n int) ([][]byte, bool) { + values := make([][]byte, n) + pos := 0 + for i := range values { + v, null, m := readLenencBytes(data[pos:]) + if m == 0 { + return nil, false + } + pos += m + if !null { + if v == nil { + v = []byte{} + } + values[i] = v + } + } + return values, true +} + +// parseBinaryRow reads a binary-protocol row and returns each value as +// text. Prepared statements here only read numbers and strings. +func parseBinaryRow(data []byte, cols []column) ([][]byte, bool) { + nullBytes := (len(cols) + 7 + 2) / 8 + if len(data) < 1+nullBytes || data[0] != pktOK { + return nil, false + } + nulls := data[1 : 1+nullBytes] + pos := 1 + nullBytes + values := make([][]byte, len(cols)) + for i, c := range cols { + bit := i + 2 + if nulls[bit/8]&(1<<(bit%8)) != 0 { + continue + } + unsigned := c.flags&flagUnsigned != 0 + fixed := func(size int) ([]byte, bool) { + if len(data) < pos+size { + return nil, false + } + b := data[pos : pos+size] + pos += size + return b, true + } + var text []byte + switch c.typ { + case typeTiny: + b, ok := fixed(1) + if !ok { + return nil, false + } + text = formatInt(uint64(b[0]), int64(int8(b[0])), unsigned) + case typeShort, typeYear: + b, ok := fixed(2) + if !ok { + return nil, false + } + u := binary.LittleEndian.Uint16(b) + text = formatInt(uint64(u), int64(int16(u)), unsigned) + case typeLong, typeInt24: + b, ok := fixed(4) + if !ok { + return nil, false + } + u := binary.LittleEndian.Uint32(b) + text = formatInt(uint64(u), int64(int32(u)), unsigned) + case typeLongLong: + b, ok := fixed(8) + if !ok { + return nil, false + } + u := binary.LittleEndian.Uint64(b) + text = formatInt(u, int64(u), unsigned) + case typeFloat: + b, ok := fixed(4) + if !ok { + return nil, false + } + text = []byte(formatFloat32(math.Float32frombits(binary.LittleEndian.Uint32(b)))) + case typeDouble: + b, ok := fixed(8) + if !ok { + return nil, false + } + text = strconv.AppendFloat(nil, math.Float64frombits(binary.LittleEndian.Uint64(b)), 'g', -1, 64) + case typeDate, typeDateTime, typeTimestamp, typeTime, typeNewDate, + typeTimestamp2, typeDateTime2, typeTime2: + // Not read by prepared statements here. + return nil, false + default: + v, _, m := readLenencBytes(data[pos:]) + if m == 0 { + return nil, false + } + pos += m + text = v + if text == nil { + text = []byte{} + } + } + values[i] = text + } + return values, true +} + +func formatInt(u uint64, s int64, unsigned bool) []byte { + if unsigned { + return strconv.AppendUint(nil, u, 10) + } + return strconv.AppendInt(nil, s, 10) +} diff --git a/internal/drivers/oracle/edit.go b/internal/drivers/oracle/edit.go new file mode 100644 index 0000000..9cf0120 --- /dev/null +++ b/internal/drivers/oracle/edit.go @@ -0,0 +1,560 @@ +package oracle + +// Applying grid changes. Values are bound as text and converted on the +// server with explicit formats (to_number on digits and an exponent, +// to_date/to_timestamp with a format mask), so nothing depends on the +// session's NLS settings. + +import ( + "strconv" + "strings" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +// maxBindBytes is the largest string or RAW value bound as one value (the +// PL/SQL limit). +const maxBindBytes = 32767 + +// numberDigits is the number of digits an Oracle NUMBER mantissa can hold. +const numberDigits = 40 + +// colType says how a column's text is converted and bound. +type colType int + +const ( + colNone colType = iota + colNumber + colBinaryFloat + colBinaryDouble + colDate + colTimestamp + colTimestampTZ + colText + colBinary + colBool +) + +// colTypeOf returns how the grid writes a column type. TIMESTAMP WITH LOCAL +// TIME ZONE, intervals, LONG, JSON, objects and the like stay read-only +// (colNone). +func colTypeOf(typeName string) colType { + t := strings.ToUpper(strings.TrimSpace(typeName)) + if strings.HasPrefix(t, "TIMESTAMP") { + switch { + case strings.Contains(t, "LOCAL"): + return colNone + case strings.Contains(t, "TIME ZONE"): + return colTimestampTZ + default: + return colTimestamp + } + } + base := t + if i := strings.IndexAny(base, "( "); i >= 0 { + base = base[:i] + } + switch base { + case "NUMBER", "FLOAT", "INTEGER", "DECIMAL": + return colNumber + case "BINARY_FLOAT": + return colBinaryFloat + case "BINARY_DOUBLE": + return colBinaryDouble + case "DATE": + return colDate + case "VARCHAR2", "NVARCHAR2", "VARCHAR", "CHAR", "NCHAR", "CLOB", "NCLOB": + return colText + case "RAW", "BLOB": + return colBinary + case "BOOLEAN": + return colBool + } + return colNone +} + +type changeOp int + +const ( + opUpdate changeOp = iota + opDelete + opInsert +) + +type planned struct { + // 1-based index of the change. + row int + op changeOp + sql string + binds []any +} + +// parseNumber reads `[-+]digits[.digits]` and returns it as +// `[-]digitsEexponent`, which to_number reads without a decimal or group +// character and so without depending on NLS settings. +func parseNumber(text string) (string, bool) { + s := strings.TrimSpace(text) + negative := false + if rest, ok := strings.CutPrefix(s, "-"); ok { + negative, s = true, rest + } else { + s = strings.TrimPrefix(s, "+") + } + intPart, frac, _ := strings.Cut(s, ".") + if (intPart == "" && frac == "") || !allDigits(intPart) || !allDigits(frac) { + return "", false + } + digits := strings.TrimLeft(intPart+frac, "0") + exponent := -len(frac) + trimmed := strings.TrimRight(digits, "0") + exponent += len(digits) - len(trimmed) + digits = trimmed + if digits == "" { + return "0", true + } + if len(digits) > numberDigits { + return "", false + } + sign := "" + if negative { + sign = "-" + } + return sign + digits + "E" + strconv.Itoa(exponent), true +} + +func allDigits(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +// floatText returns a BINARY_FLOAT/DOUBLE as an SQL expression: the +// special values by name, others as digits and an exponent for +// to_binary_float/to_binary_double. +func floatText(text string, bits int) (sqlName string, digits string, ok bool) { + v, err := strconv.ParseFloat(strings.TrimSpace(text), bits) + if err != nil { + if ne, isNum := err.(*strconv.NumError); !isNum || ne.Err != strconv.ErrRange { + return "", "", false + } + } + prefix := "binary_double" + if bits == 32 { + prefix = "binary_float" + } + switch { + case v != v: + return prefix + "_nan", "", true + case v > 0 && v*0.5 == v: + return prefix + "_infinity", "", true + case v < 0 && v*0.5 == v: + return "-" + prefix + "_infinity", "", true + } + // 1.5e+00 -> 15E-1 + e := strconv.FormatFloat(v, 'e', -1, bits) + mantissa, exp, _ := strings.Cut(e, "e") + n, _ := strconv.Atoi(exp) + intPart, frac, _ := strings.Cut(mantissa, ".") + return "", intPart + frac + "E" + strconv.Itoa(n-len(frac)), true +} + +// timestampValue is a parsed date and time with an optional offset. +type timestampValue struct { + year, month, day, hour, minute, second, nanos int + tz string +} + +// parseTimestamp reads the format the grid shows: +// `YYYY-MM-DD[ HH:MI:SS[.fffffffff]][ +HH:MM]` (`T` may separate date and +// time). tz is the offset as `+HH:MM`, empty when there is none. +func parseTimestamp(text string) (timestampValue, bool) { + var v timestampValue + num := func(s string) (int, bool) { + if s == "" || !allDigits(s) { + return 0, false + } + n, err := strconv.Atoi(s) + return n, err == nil + } + s := strings.TrimSpace(text) + if len(s) < 10 || s[4] != '-' || s[7] != '-' { + return v, false + } + var ok1, ok2, ok3 bool + v.year, ok1 = num(s[:4]) + v.month, ok2 = num(s[5:7]) + v.day, ok3 = num(s[8:10]) + if !ok1 || !ok2 || !ok3 || v.year == 0 || v.month < 1 || v.month > 12 || v.day < 1 { + return v, false + } + if time.Date(v.year, time.Month(v.month), v.day, 0, 0, 0, 0, time.UTC).Day() != v.day { + return v, false + } + rest := s[10:] + if len(rest) >= 9 && (rest[0] == ' ' || rest[0] == 'T') && rest[3] == ':' && rest[6] == ':' { + var okH, okM, okS bool + v.hour, okH = num(rest[1:3]) + v.minute, okM = num(rest[4:6]) + v.second, okS = num(rest[7:9]) + if !okH || !okM || !okS || v.hour > 23 || v.minute > 59 || v.second > 59 { + return v, false + } + rest = rest[9:] + if f, ok := strings.CutPrefix(rest, "."); ok { + n := 0 + for n < len(f) && f[n] >= '0' && f[n] <= '9' { + n++ + } + if n == 0 || n > 9 { + return v, false + } + frac, _ := num(f[:n]) + for i := n; i < 9; i++ { + frac *= 10 + } + v.nanos = frac + rest = f[n:] + } + } + rest = strings.TrimLeft(rest, " \t\r\n") + if rest != "" { + if len(rest) != 6 || (rest[0] != '+' && rest[0] != '-') || rest[3] != ':' { + return v, false + } + hh, okH := num(rest[1:3]) + mm, okM := num(rest[4:6]) + if !okH || !okM || hh > 14 || mm > 59 { + return v, false + } + v.tz = rest + } + return v, true +} + +func (v timestampValue) dateText() string { + return pad(v.year, 4) + "-" + pad(v.month, 2) + "-" + pad(v.day, 2) + " " + + pad(v.hour, 2) + ":" + pad(v.minute, 2) + ":" + pad(v.second, 2) +} + +func (v timestampValue) timestampText() string { + return v.dateText() + "." + pad(v.nanos, 9) +} + +func pad(n, width int) string { + s := strconv.Itoa(n) + for len(s) < width { + s = "0" + s + } + return s +} + +func parseHex(text string) ([]byte, bool) { + s := strings.TrimSpace(text) + if len(s)%2 != 0 { + return nil, false + } + out := make([]byte, len(s)/2) + for i := 0; i < len(s); i += 2 { + n, err := strconv.ParseUint(s[i:i+2], 16, 8) + if err != nil { + return nil, false + } + out[i/2] = byte(n) + } + return out, true +} + +func parseBool(text string) (bool, bool) { + switch strings.ToUpper(strings.TrimSpace(text)) { + case "TRUE", "1": + return true, true + case "FALSE", "0": + return false, true + } + return false, false +} + +// quoteIdent quotes an identifier. Oracle names cannot contain double quotes. +func quoteIdent(name string) (string, error) { + if name == "" || strings.ContainsAny(name, "\"\x00") { + return "", apperr.Invalidf("Invalid name: %s", name) + } + return `"` + name + `"`, nil +} + +func tooLong(name string) error { + return apperr.Invalidf("Column %s: values longer than %d bytes cannot be saved from the grid.", name, maxBindBytes) +} + +// sqlBuilder collects the binds of one statement, numbered in order of +// appearance. +type sqlBuilder struct { + binds []any +} + +func (b *sqlBuilder) bind(v any) string { + b.binds = append(b.binds, v) + return ":" + strconv.Itoa(len(b.binds)) +} + +// value returns the SQL expression for a value of col: a bind, wrapped in +// the conversion its type needs. +func (b *sqlBuilder) value(col *model.EditColumn, text string) (string, error) { + name := col.Name + bad := func(what string) error { + return apperr.Invalidf("Column %s: '%s' is not a valid %s.", name, text, what) + } + switch colTypeOf(col.TypeName) { + case colNumber: + n, ok := parseNumber(text) + if !ok { + return "", bad("number") + } + return "to_number(" + b.bind(n) + ")", nil + case colBinaryFloat, colBinaryDouble: + bits, fn := 64, "to_binary_double" + if colTypeOf(col.TypeName) == colBinaryFloat { + bits, fn = 32, "to_binary_float" + } + special, digits, ok := floatText(text, bits) + if !ok { + return "", bad("number") + } + if special != "" { + return special, nil + } + return fn + "(" + b.bind(digits) + ")", nil + case colDate: + v, ok := parseTimestamp(text) + if !ok || v.tz != "" || v.nanos != 0 { + return "", bad("date (YYYY-MM-DD HH:MI:SS)") + } + return "to_date(" + b.bind(v.dateText()) + ", 'YYYY-MM-DD HH24:MI:SS')", nil + case colTimestamp: + v, ok := parseTimestamp(text) + if !ok || v.tz != "" { + return "", bad("timestamp (YYYY-MM-DD HH:MI:SS.FF)") + } + return "to_timestamp(" + b.bind(v.timestampText()) + ", 'YYYY-MM-DD HH24:MI:SS.FF9')", nil + case colTimestampTZ: + v, ok := parseTimestamp(text) + if !ok || v.tz == "" { + return "", bad("timestamp with time zone (YYYY-MM-DD HH:MI:SS.FF +HH:MM)") + } + return "to_timestamp_tz(" + b.bind(v.timestampText()+" "+v.tz) + ", 'YYYY-MM-DD HH24:MI:SS.FF9 TZH:TZM')", nil + case colText: + if len(text) > maxBindBytes { + return "", tooLong(name) + } + return b.bind(text), nil + case colBinary: + if strings.Contains(text, "… (") { + return "", apperr.Invalidf("This value is only a preview and cannot be saved.") + } + data, ok := parseHex(text) + if !ok { + return "", bad("hexadecimal value") + } + if len(data) > maxBindBytes { + return "", tooLong(name) + } + return b.bind(data), nil + case colBool: + v, ok := parseBool(text) + if !ok { + return "", bad("boolean (TRUE or FALSE)") + } + // A literal: go-ora binds booleans with a type the server only + // accepts from clients that announce it. + if v { + return "true", nil + } + return "false", nil + } + return "", apperr.Invalidf("Column %s cannot be edited here.", name) +} + +func (b *sqlBuilder) valueOrNull(col *model.EditColumn, value *string) (string, error) { + if value == nil { + return "null", nil + } + return b.value(col, *value) +} + +// keyFilter returns `k1 = :n and k2 is null ...`. +func (b *sqlBuilder) keyFilter(keyCols []*model.EditColumn, key []*string) (string, error) { + if len(key) != len(keyCols) { + return "", apperr.Invalidf("The row key does not match the result.") + } + parts := make([]string, len(key)) + for i, col := range keyCols { + ident, err := quoteIdent(col.Name) + if err != nil { + return "", err + } + if key[i] == nil { + parts[i] = ident + " is null" + continue + } + expr, err := b.value(col, *key[i]) + if err != nil { + return "", err + } + parts[i] = ident + " = " + expr + } + return strings.Join(parts, " and "), nil +} + +func editColumn(target *model.EditTarget, index int) (*model.EditColumn, error) { + if index < 0 || index >= len(target.Columns) || target.Columns[index] == nil { + return nil, apperr.Invalidf("Result column %d cannot be edited.", index+1) + } + return target.Columns[index], nil +} + +type columnValue struct { + col *model.EditColumn + value *string +} + +// changeValues returns the values by table column; a column given twice +// keeps the last value. +func changeValues(target *model.EditTarget, values []model.CellValue) ([]columnValue, error) { + out := make([]columnValue, 0, len(values)) + for _, v := range values { + col, err := editColumn(target, v.Column) + if err != nil { + return nil, err + } + replaced := false + for i := range out { + if out[i].col.Name == col.Name { + out[i].value = v.Value + replaced = true + break + } + } + if !replaced { + out = append(out, columnValue{col: col, value: v.Value}) + } + } + return out, nil +} + +// planChanges builds every statement before anything runs, so bad input +// changes nothing. +func planChanges(req model.ApplyRequest) ([]planned, error) { + target := &req.Target + table, err := quoteIdent(target.Table) + if err != nil { + return nil, err + } + if target.Schema != nil { + schema, err := quoteIdent(*target.Schema) + if err != nil { + return nil, err + } + table = schema + "." + table + } + keyCols := make([]*model.EditColumn, len(target.Key)) + for i, k := range target.Key { + if keyCols[i], err = editColumn(target, k); err != nil { + return nil, err + } + } + out := make([]planned, 0, len(req.Changes)) + for n, change := range req.Changes { + var b sqlBuilder + p := planned{row: n + 1} + switch change.Op { + case model.OpUpdate: + values, err := changeValues(target, change.Values) + if err != nil { + return nil, err + } + if len(values) == 0 { + continue + } + sets := make([]string, len(values)) + for i, v := range values { + expr, err := b.valueOrNull(v.col, v.value) + if err != nil { + return nil, err + } + ident, err := quoteIdent(v.col.Name) + if err != nil { + return nil, err + } + sets[i] = ident + " = " + expr + } + filter, err := b.keyFilter(keyCols, change.Key) + if err != nil { + return nil, err + } + p.op = opUpdate + p.sql = "update " + table + " set " + strings.Join(sets, ", ") + " where " + filter + case model.OpDelete: + filter, err := b.keyFilter(keyCols, change.Key) + if err != nil { + return nil, err + } + p.op = opDelete + p.sql = "delete from " + table + " where " + filter + case model.OpInsert: + values, err := changeValues(target, change.Values) + if err != nil { + return nil, err + } + p.op = opInsert + if len(values) == 0 { + // Oracle has no DEFAULT VALUES: name one column as DEFAULT. + var first *model.EditColumn + for _, c := range target.Columns { + if c != nil { + first = c + break + } + } + if first == nil { + return nil, apperr.Invalidf("This result has no editable columns.") + } + ident, err := quoteIdent(first.Name) + if err != nil { + return nil, err + } + p.sql = "insert into " + table + " (" + ident + ") values (default)" + } else { + names := make([]string, len(values)) + exprs := make([]string, len(values)) + for i, v := range values { + if names[i], err = quoteIdent(v.col.Name); err != nil { + return nil, err + } + if exprs[i], err = b.valueOrNull(v.col, v.value); err != nil { + return nil, err + } + } + p.sql = "insert into " + table + " (" + strings.Join(names, ", ") + ") values (" + + strings.Join(exprs, ", ") + ")" + } + default: + return nil, apperr.Invalidf("Unknown change: %s.", change.Op) + } + p.binds = b.binds + out = append(out, p) + } + return out, nil +} + +func notSaved(row int, matched int64) error { + if matched == 0 { + return apperr.Newf(apperr.Database, + "Row %d was not saved: 0 rows matched its key (changed or removed by someone else).", row) + } + return apperr.Newf(apperr.Database, "Row %d was not saved: %d rows matched its key.", row, matched) +} diff --git a/internal/drivers/oracle/goora.go b/internal/drivers/oracle/goora.go new file mode 100644 index 0000000..c519838 --- /dev/null +++ b/internal/drivers/oracle/goora.go @@ -0,0 +1,131 @@ +package oracle + +// go-ora keeps some of what a client like this needs unexported: the full +// column descriptions (it exports only the type name), the network session +// (to interrupt a fetch, not only an execute) and the fetch size of the next +// query. These helpers reach them by reflection, checking each field's type +// so that a different go-ora version degrades (default fetch size, columns +// without detail, no interrupt while fetching) instead of misbehaving. + +import ( + "context" + "reflect" + + goora "github.com/sijms/go-ora/v2" + "github.com/sijms/go-ora/v2/configurations" + "github.com/sijms/go-ora/v2/network" +) + +var ( + paramsType = reflect.TypeOf((*[]goora.ParameterInfo)(nil)) + sessionType = reflect.TypeOf((*network.Session)(nil)) + configType = reflect.TypeOf((*configurations.ConnectionConfig)(nil)) +) + +// describe returns the column descriptions of the current result set, or nil +// when go-ora does not keep them where expected. +func describe(ds *goora.DataSet) []goora.ParameterInfo { + v := reflect.ValueOf(ds).Elem() + sets, idx := v.FieldByName("resultSets"), v.FieldByName("index") + if !sets.IsValid() || sets.Kind() != reflect.Slice || !idx.IsValid() || idx.Kind() != reflect.Int { + return nil + } + i := int(idx.Int()) + if i < 0 || i >= sets.Len() { + return nil + } + cols := sets.Index(i).FieldByName("cols") + if !cols.IsValid() || cols.Type() != paramsType || cols.IsNil() { + return nil + } + // A copy: go-ora keeps using its own. + params := append([]goora.ParameterInfo(nil), *(*[]goora.ParameterInfo)(cols.UnsafePointer())...) + lobDefines(ds, params) + return params +} + +// lobDefines undoes go-ora's renaming of LOB columns. To fetch LOB values +// with the rows, go-ora defines CLOB/NCLOB columns as LONG VARCHAR and +// BLOB (and VECTOR) columns as LONG RAW, and keeps those types in the column +// description. The server itself never describes a column as LONG VARCHAR, +// and describes LONG RAW only when the statement has a LONG column. +func lobDefines(ds *goora.DataSet, cols []goora.ParameterInfo) { + hasLong := true + v := reflect.ValueOf(ds).Elem() + sets, idx := v.FieldByName("resultSets"), v.FieldByName("index") + if sets.IsValid() && sets.Kind() == reflect.Slice && idx.IsValid() && idx.Kind() == reflect.Int { + if i := int(idx.Int()); i >= 0 && i < sets.Len() { + if parent := sets.Index(i).FieldByName("parent"); parent.IsValid() && parent.Kind() == reflect.Interface && !parent.IsNil() { + stmt := parent.Elem() + if stmt.Kind() == reflect.Pointer && !stmt.IsNil() && stmt.Elem().Kind() == reflect.Struct { + if f := stmt.Elem().FieldByName("_hasLONG"); f.IsValid() && f.Kind() == reflect.Bool { + hasLong = f.Bool() + } + } + } + } + } + for i := range cols { + switch { + case cols[i].DataType == goora.LongVarChar: + cols[i].DataType = goora.OCIClobLocator + case cols[i].DataType == goora.LongRaw && !hasLong: + cols[i].DataType = goora.OCIBlobLocator + } + } +} + +func connField(conn *goora.Connection, name string, typ reflect.Type) reflect.Value { + if conn == nil { + return reflect.Value{} + } + f := reflect.ValueOf(conn).Elem().FieldByName(name) + if !f.IsValid() || f.Type() != typ || f.IsNil() { + return reflect.Value{} + } + return f +} + +// sessionOf returns the network session of a connection. +func sessionOf(conn *goora.Connection) *network.Session { + f := connField(conn, "session", sessionType) + if !f.IsValid() { + return nil + } + return (*network.Session)(f.UnsafePointer()) +} + +// setPrefetch sets how many rows the next query fetches per round trip. +// go-ora sizes the fetch by row width when the value is its default, 25. +func setPrefetch(conn *goora.Connection, rows int) { + f := connField(conn, "connOption", configType) + if !f.IsValid() { + return + } + if rows == 25 { + rows = 26 + } + (*configurations.ConnectionConfig)(f.UnsafePointer()).PrefetchRows = rows +} + +// watch makes ctx interrupt the call that runs until the returned stop is +// called: the server receives a break and answers ORA-01013. go-ora does this +// for execute calls only; fetching more rows needs it too. +func watch(ctx context.Context, conn *goora.Connection) (stop func()) { + sess := sessionOf(conn) + if sess == nil || ctx.Done() == nil { + return func() {} + } + done := sess.StartContext(ctx) + return func() { sess.EndContext(done) } +} + +// disconnect closes the socket of a connection without logging off, for a +// connection whose replies can no longer be read. +func disconnect(conn *goora.Connection) { + if sess := sessionOf(conn); sess != nil { + sess.Disconnect() + return + } + _ = conn.Close() +} diff --git a/internal/drivers/oracle/integration_test.go b/internal/drivers/oracle/integration_test.go new file mode 100644 index 0000000..bcf559d --- /dev/null +++ b/internal/drivers/oracle/integration_test.go @@ -0,0 +1,1041 @@ +package oracle + +// Tests against a real server. They only run with LQ_ORA_HOST set (and +// optionally LQ_ORA_PORT, LQ_ORA_SERVICE, LQ_ORA_USER, LQ_ORA_PASSWORD). They +// create objects in the test user's own schema only, and drop them. + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "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 oraProfile(t *testing.T) (model.ConnectionProfile, *string) { + t.Helper() + host := os.Getenv("LQ_ORA_HOST") + if host == "" { + t.Skip("LQ_ORA_HOST is not set") + } + p := model.DefaultProfile() + p.Name = "test" + p.Engine = model.Oracle + p.Host = host + p.Port = 1521 + if n, err := strconv.ParseUint(os.Getenv("LQ_ORA_PORT"), 10, 16); err == nil { + p.Port = uint16(n) + } + p.User = env("LQ_ORA_USER", "system") + p.Database = env("LQ_ORA_SERVICE", "FREEPDB1") + p.OracleConnectType = model.OracleService + var password *string + if pw := os.Getenv("LQ_ORA_PASSWORD"); pw != "" { + password = &pw + } + return p, password +} + +func open(t *testing.T, p model.ConnectionProfile, password *string) *Session { + t.Helper() + s, err := Connect(context.Background(), p, password) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func oraSession(t *testing.T) *Session { + t.Helper() + p, pw := oraProfile(t) + return open(t, p, pw) +} + +func execMax(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 run(t *testing.T, s *Session, sql string) *model.ExecResult { + t.Helper() + return execMax(t, s, sql, 100) +} + +func tryRun(s *Session, sql string) bool { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: sql}) + return err == nil +} + +func text(v *string) string { + if v == nil { + return "NULL" + } + return *v +} + +func oneRow(t *testing.T, s *Session, sql string) []string { + t.Helper() + r := execMax(t, s, sql, 10) + if len(r.Rows) == 0 { + t.Fatalf("%s: no rows", sql) + } + out := make([]string, len(r.Rows[0])) + for i, v := range r.Rows[0] { + out[i] = text(v) + } + return out +} + +func firstColumn(rows []model.Row) []string { + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = text(r[0]) + } + return out +} + +func TestOracleTypesLimitsAndOutput(t *testing.T) { + s := oraSession(t) + if !strings.HasPrefix(s.ServerVersion(), "Oracle ") || len(s.ServerVersion()) < 10 { + t.Errorf("server version %q", s.ServerVersion()) + } + if s.CurrentUser() == nil || s.CurrentSchema() == nil { + t.Errorf("user %v, schema %v", s.CurrentUser(), s.CurrentSchema()) + } + + r := execMax(t, s, `select 1, 1.5, 12345678901234567890.123456789, cast(null as varchar2(10)), 'texto', + date '2024-02-29', timestamp '2024-02-29 13:45:10.25', + hextoraw('DEADBEEF'), interval '3' day, to_clob('clob'), binary_double_infinity, + interval '1-2' year to month, interval '-1 02:03:04.5' day to second(3), + timestamp '2025-10-31 11:52:15.456 -06:00', cast(0.1 as binary_double), + cast(1.5 as binary_float), -0.5, 1e30, n'olá', cast('ab' as char(5)) + from dual;`, 10) + v := make([]string, len(r.Rows[0])) + for i, c := range r.Rows[0] { + v[i] = text(c) + } + want := map[int]string{ + 0: "1", 1: "1.5", 2: "12345678901234567890.123456789", 3: "NULL", 4: "texto", + 5: "2024-02-29 00:00:00", 7: "DEADBEEF", 8: "P3DT0H0M0.000000000S", 9: "clob", 10: "Inf", + 11: "P1Y2M", 12: "P-1DT-2H-3M-4.-500000000S", 13: "2025-10-31 11:52:15.456000000 -06:00", + 14: "0.1", 15: "1.5", 16: "-0.5", 17: "1" + strings.Repeat("0", 30), 18: "olá", 19: "ab ", + } + for i, w := range want { + if v[i] != w { + t.Errorf("column %d (%s): got %q, want %q", i+1, r.Columns[i].TypeName, v[i], w) + } + } + if !strings.HasPrefix(v[6], "2024-02-29 13:45:10.25") { + t.Errorf("timestamp: %q", v[6]) + } + kinds := []model.ValueKind{ + model.KindNumber, model.KindNumber, model.KindNumber, model.KindText, model.KindText, + model.KindTemporal, model.KindTemporal, model.KindBinary, model.KindTemporal, model.KindText, + model.KindNumber, model.KindTemporal, model.KindTemporal, model.KindTemporal, model.KindNumber, + model.KindNumber, model.KindNumber, model.KindNumber, model.KindText, model.KindText, + } + for i, k := range kinds { + if r.Columns[i].Kind != k { + t.Errorf("column %d (%s): kind %s, want %s", i+1, r.Columns[i].TypeName, r.Columns[i].Kind, k) + } + } + types := map[int]string{ + 0: "NUMBER", 5: "DATE", 6: "TIMESTAMP(9)", 7: "RAW(4)", 9: "CLOB", 10: "BINARY_DOUBLE", + 12: "INTERVAL DAY(2) TO SECOND(3)", 13: "TIMESTAMP(9) WITH TIME ZONE", 15: "BINARY_FLOAT", + 4: "CHAR(5)", 18: "NCHAR(3)", 19: "CHAR(5)", + } + for i, w := range types { + if r.Columns[i].TypeName != w { + t.Errorf("column %d: type %q, want %q", i+1, r.Columns[i].TypeName, w) + } + } + + r = execMax(t, s, "select level from dual connect by level <= 1000", 100) + if len(r.Rows) != 100 || !r.Truncated { + t.Errorf("limit: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + r = execMax(t, s, "select level from dual connect by level <= 100", 100) + if len(r.Rows) != 100 || r.Truncated { + t.Errorf("exact limit: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "select * from missing_table", MaxRows: 10}) + e := apperr.From(err) + if e == nil || e.Code != "ORA-00942" || e.Kind != apperr.Database { + t.Fatalf("missing table: %#v", e) + } + if e.Position == nil || *e.Position != 14 { + t.Errorf("position: %v", e.Position) + } + if strings.HasPrefix(e.Message, "ORA-") { + t.Errorf("message keeps the code: %q", e.Message) + } + + r = execMax(t, s, "begin dbms_output.put_line('olá'); dbms_output.put_line(null); dbms_output.put_line('mundo'); end;\n/", 0) + if !reflect.DeepEqual(r.Notices, []string{"olá", "", "mundo"}) { + t.Errorf("notices: %q", r.Notices) + } + // Many lines come back in order, in several round trips. + r = execMax(t, s, "begin for i in 1 .. 2500 loop dbms_output.put_line('line ' || i || ' ' || rpad('x', mod(i, 50), 'y')); end loop; end;", 0) + if len(r.Notices) != 2500 || r.Notices[0] != "line 1 x" || !strings.HasPrefix(r.Notices[2499], "line 2500 ") { + t.Errorf("many notices: %d", len(r.Notices)) + } + + schemas, err := s.ListSchemas(context.Background()) + if err != nil || len(schemas) == 0 || schemas[0] != *s.CurrentSchema() { + t.Errorf("schemas: %v %v", schemas, err) + } +} + +// ERP tables (Protheus SA1010 and the like) have hundreds of columns, many of +// them blank in every row, so the server sends rows with repeated-column bit +// vectors and responses that span many packets. +func TestOracleWideRowsWithRepeatedValues(t *testing.T) { + s := oraSession(t) + const cols, rows = 200, 3000 + expr := func(c int) string { + switch c % 4 { + case 0: + return "rpad(' ', 10)" + case 1: + return fmt.Sprintf("'V' || level || '_%d'", c) + case 2: + return "to_char(trunc(level / 7))" + } + return fmt.Sprintf("mod(level, 2) * %d", c) + } + expected := func(row, c int) string { + level := row + 1 + switch c % 4 { + case 0: + return strings.Repeat(" ", 10) + case 1: + return fmt.Sprintf("V%d_%d", level, c) + case 2: + return strconv.Itoa(level / 7) + } + return strconv.Itoa((level % 2) * c) + } + for _, tc := range []struct { + table string + lob bool + }{{"lq_wide", false}, {"lq_wide_lob", true}} { + tryRun(s, "drop table "+tc.table+" purge") + var ddl, names, values []string + for c := 0; c < cols; c++ { + ty := "varchar2(40)" + if c%4 == 3 { + ty = "number" + } + ddl = append(ddl, fmt.Sprintf("c%d %s", c, ty)) + names = append(names, fmt.Sprintf("c%d", c)) + values = append(values, expr(c)) + } + ddl = append(ddl, "d_e_l_e_t_ varchar2(1)", "r_e_c_n_o_ number primary key") + if tc.lob { + ddl = append(ddl, "memo blob") + } + run(t, s, "create table "+tc.table+" ("+strings.Join(ddl, ", ")+")") + t.Cleanup(func() { tryRun(s, "drop table "+tc.table+" purge") }) + run(t, s, fmt.Sprintf("insert into %s (%s, d_e_l_e_t_, r_e_c_n_o_) select %s, ' ', level from dual connect by level <= %d", + tc.table, strings.Join(names, ", "), strings.Join(values, ", "), rows)) + sql := "select * from " + tc.table + " order by r_e_c_n_o_" + for _, limit := range []int{500, 500, 200, 0} { + r := execMax(t, s, sql, limit) + n := limit + if limit == 0 { + n = rows + } + if len(r.Rows) != n { + t.Fatalf("%s limit %d: %d rows", tc.table, limit, len(r.Rows)) + } + for i, row := range r.Rows { + if text(row[cols+1]) != strconv.Itoa(i+1) { + t.Fatalf("%s row %d: key %s", tc.table, i+1, text(row[cols+1])) + } + for _, c := range []int{0, 1, 2, 3, 98, 99, 101, 102, 199} { + if got := text(row[c]); got != expected(i, c) { + t.Fatalf("%s row %d column c%d: got %q, want %q", tc.table, i+1, c, got, expected(i, c)) + } + } + } + } + // The session is still usable afterwards. + if got := oneRow(t, s, "select count(*) from "+tc.table)[0]; got != strconv.Itoa(rows) { + t.Fatalf("count: %s", got) + } + run(t, s, "drop table "+tc.table+" purge") + } +} + +// Queries returning CLOBs run again and again in one session, including +// after the server parses them again and after a failure while the LOB +// column is defined. +func TestOracleClobQueriesRunRepeatedly(t *testing.T) { + s := oraSession(t) + schema := *s.CurrentSchema() + tryRun(s, "drop table lq_clob purge") + run(t, s, "create table lq_clob (id number primary key, doc clob)") + t.Cleanup(func() { tryRun(s, "drop table lq_clob purge") }) + // Values longer than 4000 characters, which no VARCHAR2 define can hold. + run(t, s, `insert into lq_clob + select level, to_clob(rpad('a', 4000, 'a')) || rpad('b', 4000, 'b') || level + from dual connect by level <= 3`) + longDoc := func(id int) string { return strings.Repeat("a", 4000) + strings.Repeat("b", 4000) + strconv.Itoa(id) } + queries := []struct { + sql string + limit int + check func(rows []model.Row) error + }{ + {"select dbms_metadata.get_ddl('TABLE', 'LQ_CLOB') from dual", 100, func(rows []model.Row) error { + if len(rows) != 1 || !strings.Contains(text(rows[0][0]), "CREATE TABLE") || !strings.Contains(text(rows[0][0]), "LQ_CLOB") { + return fmt.Errorf("ddl: %v", firstColumn(rows)) + } + return nil + }}, + {"select to_clob('LowQuery ' || level) from dual connect by level <= 3", 100, func(rows []model.Row) error { + if got := firstColumn(rows); !reflect.DeepEqual(got, []string{"LowQuery 1", "LowQuery 2", "LowQuery 3"}) { + return fmt.Errorf("got %q", got) + } + return nil + }}, + {"select id, doc from lq_clob order by id", 100, func(rows []model.Row) error { + if len(rows) != 3 { + return fmt.Errorf("%d rows", len(rows)) + } + for i, row := range rows { + if text(row[0]) != strconv.Itoa(i+1) || text(row[1]) != longDoc(i+1) { + return fmt.Errorf("row %d differs", i+1) + } + } + return nil + }}, + // The first row only: the cursor is closed with rows left to fetch. + {"select doc from lq_clob order by id", 1, func(rows []model.Row) error { + if len(rows) != 1 || text(rows[0][0]) != longDoc(1) { + return fmt.Errorf("%d rows", len(rows)) + } + return nil + }}, + } + invalidate := "begin dbms_stats.gather_table_stats(user, 'LQ_CLOB', no_invalidate => false); end;" + for _, q := range queries { + for attempt := 1; attempt <= 5; attempt++ { + if attempt == 3 { + run(t, s, invalidate) + } + if err := q.check(execMax(t, s, q.sql, q.limit).Rows); err != nil { + t.Fatalf("%s: run %d: %v", q.sql, attempt, err) + } + } + } + // A query that fails while its LOB column is defined (ORA-01476 here), + // then succeeds once the data changes. + tryRun(s, "drop table lq_clob_flag purge") + run(t, s, "create table lq_clob_flag (n number)") + t.Cleanup(func() { tryRun(s, "drop table lq_clob_flag purge") }) + run(t, s, "insert into lq_clob_flag values (0)") + flagged := "select to_clob('n=' || (select 1 / n from lq_clob_flag)) from dual" + for attempt := 1; attempt <= 2; attempt++ { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: flagged, MaxRows: 100}) + if err == nil || !strings.Contains(err.Error(), "ORA-01476") { + t.Fatalf("run %d: %v", attempt, err) + } + } + run(t, s, "update lq_clob_flag set n = 1") + for attempt := 3; attempt <= 5; attempt++ { + if got := oneRow(t, s, flagged)[0]; got != "n=1" { + t.Fatalf("run %d: %q", attempt, got) + } + } + run(t, s, "drop table lq_clob_flag purge") + // Show DDL five times in a row; the table has no comments, so one of its + // queries fails every time. + for attempt := 1; attempt <= 5; attempt++ { + ddl, err := s.ObjectDDL(context.Background(), schema, "LQ_CLOB", "table") + if err != nil || !strings.Contains(ddl, "LQ_CLOB") { + t.Fatalf("Show DDL run %d: %v\n%s", attempt, err, ddl) + } + } + if got := oneRow(t, s, "select count(*) from lq_clob")[0]; got != "3" { + t.Fatalf("count: %s", got) + } + run(t, s, "drop table lq_clob purge") +} + +func TestOracleConnectsThroughTNSAlias(t *testing.T) { + base, pw := oraProfile(t) + // A Latin-1 tnsnames.ora with a domain-qualified alias, as corporate files + // often are. + dir := t.TempDir() + file := []byte("# Produ\xe7\xe3o\n") + file = append(file, fmt.Sprintf("LQTEST.WORLD =\n (DESCRIPTION =\n (ADDRESS = (PROTOCOL = TCP)(HOST = %s)(PORT = %d))\n (CONNECT_DATA = (SERVICE_NAME = %s))\n )\n", + base.Host, base.Port, base.Database)...) + if err := os.WriteFile(filepath.Join(dir, "tnsnames.ora"), file, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "sqlnet.ora"), []byte("NAMES.DEFAULT_DOMAIN = WORLD\n"), 0o600); err != nil { + t.Fatal(err) + } + + // Folder chosen in the profile. + p := base + p.OracleConnectType = model.OracleTNS + p.TnsAlias = "lqtest" + p.ConfigDir = &dir + s := open(t, p, pw) + if got := oneRow(t, s, "select 1 from dual")[0]; got != "1" { + t.Fatalf("got %q", got) + } + + // Automatic discovery through TNS_ADMIN. + t.Setenv("TNS_ADMIN", dir) + auto := p + auto.ConfigDir = nil + s = open(t, auto, pw) + if got := oneRow(t, s, "select 2 from dual")[0]; got != "2" { + t.Fatalf("got %q", got) + } + + // A custom connect string: an alias, an Easy Connect string and a + // descriptor. + custom := base + custom.OracleConnectType = model.OracleCustom + for _, cs := range []string{ + "lqtest", + fmt.Sprintf("%s:%d/%s", base.Host, base.Port, base.Database), + fmt.Sprintf("tcp://%s:%d/%s", base.Host, base.Port, base.Database), + fmt.Sprintf("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d))(CONNECT_DATA=(SERVICE_NAME=%s)))", base.Host, base.Port, base.Database), + } { + custom.ConnectString = cs + s = open(t, custom, pw) + if got := oneRow(t, s, "select 3 from dual")[0]; got != "3" { + t.Fatalf("%s: got %q", cs, got) + } + } + + // Unknown alias names the files that were searched. + missing := auto + missing.TnsAlias = "nope" + _, err := Connect(context.Background(), missing, pw) + if err == nil || !strings.Contains(apperr.From(err).Message, "tnsnames.ora") { + t.Fatalf("unknown alias: %v", err) + } +} + +func TestOracleWrongPasswordIsAConnectionError(t *testing.T) { + p, _ := oraProfile(t) + wrong := "definitely-not-the-password" + _, err := Connect(context.Background(), p, &wrong) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Connection || e.Code != "ORA-01017" { + t.Fatalf("got %#v", e) + } +} + +func TestOracleResultViewSQL(t *testing.T) { + fixtures.CheckView(t, oraSession(t), "oracle") +} + +func TestOracleDDLSQL(t *testing.T) { + s := oraSession(t) + fixtures.CheckDDL(t, s, "oracle", *s.CurrentSchema()) +} + +func TestOracleCatalog(t *testing.T) { + s := oraSession(t) + ctx := context.Background() + schema := *s.CurrentSchema() + tryRun(s, "drop table lq_cat purge") + run(t, s, "create table lq_cat (id number(10) primary key, name varchar2(30) default 'x' not null, price number(8,2), raw_v raw(16))") + t.Cleanup(func() { tryRun(s, "drop table lq_cat purge") }) + objects, err := s.ListObjects(ctx, schema) + if err != nil { + t.Fatal(err) + } + found := false + for _, o := range objects { + if o.Name == "LQ_CAT" && o.Kind == "table" { + found = true + } + } + if !found { + t.Fatalf("LQ_CAT not listed: %v", objects) + } + cols, err := s.ListColumns(ctx, schema, "LQ_CAT") + if err != nil { + t.Fatal(err) + } + want := []model.DbColumn{ + {Name: "ID", TypeName: "NUMBER(10)", PrimaryKey: true}, + {Name: "NAME", TypeName: "VARCHAR2(30)", DefaultValue: model.Str("'x'")}, + {Name: "PRICE", TypeName: "NUMBER(8,2)", Nullable: true}, + {Name: "RAW_V", TypeName: "RAW(16)", Nullable: true}, + } + if !reflect.DeepEqual(cols, want) { + t.Fatalf("columns:\n%+v\nwant\n%+v", cols, want) + } + if _, err := s.ObjectDDL(ctx, schema, "LQ_CAT", "index"); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("index DDL: %v", err) + } +} + +func TestOracleTransactions(t *testing.T) { + s := oraSession(t) + p, pw := oraProfile(t) + other := open(t, p, pw) + tryRun(s, "drop table lq_tx purge") + run(t, s, "create table lq_tx (id number primary key, v varchar2(10))") + t.Cleanup(func() { tryRun(s, "drop table lq_tx purge") }) + + // Autocommit: other sessions see DML at once. + r := run(t, s, "insert into lq_tx values (1, 'a')") + if r.RowsAffected == nil || *r.RowsAffected != 1 || r.InTransaction { + t.Fatalf("insert: %+v", r) + } + if got := firstColumn(run(t, other, "select v from lq_tx").Rows); !reflect.DeepEqual(got, []string{"a"}) { + t.Fatalf("other session: %v", got) + } + + // Manual mode keeps the transaction open until COMMIT or ROLLBACK. + if st, err := s.SetAutocommit(context.Background(), false); err != nil || st.Autocommit { + t.Fatalf("set autocommit: %+v %v", st, err) + } + if r := run(t, s, "update lq_tx set v = 'b'"); !r.InTransaction { + t.Fatal("update did not open a transaction") + } + if got := firstColumn(run(t, other, "select v from lq_tx").Rows); !reflect.DeepEqual(got, []string{"a"}) { + t.Fatalf("uncommitted change visible: %v", got) + } + if st, err := s.EndTransaction(context.Background(), false); err != nil || st.InTransaction { + t.Fatalf("rollback: %+v %v", st, err) + } + if got := firstColumn(run(t, s, "select v from lq_tx").Rows); !reflect.DeepEqual(got, []string{"a"}) { + t.Fatalf("rollback kept the change: %v", got) + } + run(t, s, "begin update lq_tx set v = 'c'; end;") + if !s.TxState().InTransaction { + t.Fatal("PL/SQL did not open a transaction") + } + if r := run(t, s, "commit"); r.InTransaction { + t.Fatal("COMMIT left the transaction open") + } + if got := firstColumn(run(t, other, "select v from lq_tx").Rows); !reflect.DeepEqual(got, []string{"c"}) { + t.Fatalf("commit not visible: %v", got) + } + // Turning autocommit back on commits pending work. + run(t, s, "update lq_tx set v = 'd'") + if st, err := s.SetAutocommit(context.Background(), true); err != nil || st.InTransaction || !st.Autocommit { + t.Fatalf("autocommit on: %+v %v", st, err) + } + if got := firstColumn(run(t, other, "select v from lq_tx").Rows); !reflect.DeepEqual(got, []string{"d"}) { + t.Fatalf("pending work not committed: %v", got) + } +} + +func TestOracleCancel(t *testing.T) { + s := oraSession(t) + slow := "select count(*) from all_objects a, all_objects b, all_objects c" + for _, tc := range []struct { + name string + sql string + }{ + {"execute", slow}, + // The first rows come at once, then slowly, so the cancel arrives + // while fetching. + {"fetch", `select n, case when n > 2500 then (select count(*) from all_objects o where o.object_id > n) end c + from (select level n from dual connect by level <= 100000)`}, + {"plsql", "begin loop null; end loop; end;"}, + } { + t.Run(tc.name, func(t *testing.T) { + done := make(chan error, 1) + started := time.Now() + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: tc.sql, MaxRows: 0}) + done <- err + }() + time.Sleep(1500 * time.Millisecond) + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if apperr.From(err).Kind != apperr.Cancelled { + t.Fatalf("got %v", err) + } + case <-time.After(30 * time.Second): + t.Fatal("the statement was not interrupted") + } + if elapsed := time.Since(started); elapsed > 20*time.Second { + t.Errorf("cancel took %v", elapsed) + } + // The session is still usable. + if got := oneRow(t, s, "select 'ok' from dual")[0]; got != "ok" { + t.Fatalf("after cancel: %q", got) + } + }) + } + + // A context that ends stops the statement too. + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _, err := s.Execute(ctx, model.ExecRequest{SQL: slow}) + if apperr.From(err).Kind != apperr.Cancelled { + t.Fatalf("deadline: %v", err) + } + if got := oneRow(t, s, "select 'ok' from dual")[0]; got != "ok" { + t.Fatalf("after deadline: %q", got) + } +} + +func TestOracleStream(t *testing.T) { + s := oraSession(t) + // A BLOB larger than the preview, built in PL/SQL: SQL caps RAW values. + tryRun(s, "drop table lq_stream purge") + run(t, s, "create table lq_stream (b blob)") + t.Cleanup(func() { tryRun(s, "drop table lq_stream purge") }) + run(t, s, `declare + b blob; + begin + dbms_lob.createtemporary(b, true); + for i in 1 .. 20 loop + dbms_lob.writeappend(b, 2000, utl_raw.copies(hextoraw('AB'), 2000)); + end loop; + insert into lq_stream values (b); + end;`) + sink := make(chan drivers.StreamEvent, 4) + var columns []model.ColumnInfo + var rows []model.Row + done := make(chan struct{}) + go func() { + for ev := range sink { + if ev.Columns != nil { + columns = ev.Columns + } + if len(ev.Rows) > drivers.StreamBatch { + t.Errorf("batch of %d rows", len(ev.Rows)) + } + rows = append(rows, ev.Rows...) + } + close(done) + }() + n, err := s.Stream(context.Background(), + `select n, 'row ' || n l, case when n = 1 then s.b end b + from lq_stream s cross join (select level n from dual connect by level <= 1234) + order by n;`, sink) + close(sink) + <-done + if err != nil || n != 1234 || len(rows) != 1234 { + t.Fatalf("stream: %d rows, %v", n, err) + } + if len(columns) != 3 || columns[2].Kind != model.KindBinary || columns[2].TypeName != "BLOB" { + t.Fatalf("columns: %+v", columns) + } + // Values are in full: binary values are not cut to the preview. + if got := text(rows[0][2]); len(got) != 80000 || strings.Contains(got, "…") { + t.Fatalf("blob: %d characters", len(got)) + } + if text(rows[1233][0]) != "1234" || text(rows[1233][1]) != "row 1234" || rows[1233][2] != nil { + t.Fatalf("last row: %v", text(rows[1233][0])) + } + + // A stopped receiver ends the stream. + ctx, cancel := context.WithCancel(context.Background()) + sink = make(chan drivers.StreamEvent) + go func() { + <-sink + cancel() + }() + _, err = s.Stream(ctx, "select level from dual connect by level <= 100000", sink) + if apperr.From(err).Kind != apperr.Cancelled { + t.Fatalf("stopped stream: %v", err) + } + if got := oneRow(t, s, "select 'ok' from dual")[0]; got != "ok" { + t.Fatalf("after stream: %q", got) + } +} + +// --- Editable results --- + +func targetOf(t *testing.T, r *model.ExecResult) *model.EditTarget { + t.Helper() + if r.Editable == nil { + t.Fatalf("read-only: %v", text(r.ReadOnlyReason)) + } + return r.Editable +} + +func reasonOf(t *testing.T, r *model.ExecResult) string { + t.Helper() + if r.Editable != nil { + t.Fatalf("editable: %+v", r.Editable) + } + if r.ReadOnlyReason == nil { + t.Fatal("no read-only reason") + } + return *r.ReadOnlyReason +} + +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 cv(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func TestOracleEditDetection(t *testing.T) { + s := oraSession(t) + tables := []string{"lq_edit_t", "lq_edit_nokey", "lq_edit_uk"} + for _, tb := range tables { + tryRun(s, "drop table "+tb+" purge") + } + t.Cleanup(func() { + for _, tb := range tables { + tryRun(s, "drop table "+tb+" purge") + } + }) + run(t, s, "create table lq_edit_t (id number(10) primary key, name varchar2(50), qty number(10,2))") + run(t, s, "create table lq_edit_nokey (a number, b varchar2(10))") + run(t, s, "create table lq_edit_uk (code varchar2(10) not null, v number, constraint lq_edit_uk_u unique (code))") + + tg := targetOf(t, run(t, s, "select id, name, qty * 2 as dbl from lq_edit_t")) + if tg.Table != "LQ_EDIT_T" || *tg.Schema != *s.CurrentSchema() || !reflect.DeepEqual(tg.Key, []int{0}) || + tg.Columns[1].Name != "NAME" || tg.Columns[2] != nil { + t.Fatalf("target: %+v", tg) + } + if k := targetOf(t, run(t, s, "select name, e.id from lq_edit_t e where id > 0 order by id")).Key; !reflect.DeepEqual(k, []int{1}) { + t.Fatalf("key: %v", k) + } + tg = targetOf(t, run(t, s, "select * from lq_edit_t")) + if !reflect.DeepEqual(tg.Key, []int{0}) || tg.Columns[2].TypeName != "NUMBER(10,2)" { + t.Fatalf("star: %+v", tg) + } + if r := reasonOf(t, run(t, s, "select a.id, b.name from lq_edit_t a join lq_edit_t b on a.id = b.id")); !strings.Contains(r, "several tables") { + t.Fatal(r) + } + if r := reasonOf(t, run(t, s, "select * from lq_edit_nokey")); !strings.Contains(r, "no primary key") { + t.Fatal(r) + } + if r := reasonOf(t, run(t, s, "select name from lq_edit_t")); !strings.Contains(r, "(ID)") { + t.Fatal(r) + } + if k := targetOf(t, run(t, s, "select v, code from lq_edit_uk")).Key; !reflect.DeepEqual(k, []int{1}) { + t.Fatalf("unique key: %v", k) + } + reasonOf(t, run(t, s, "select name, count(*) from lq_edit_t group by name")) + reasonOf(t, run(t, s, "select sysdate from dual")) + if r := run(t, s, "insert into lq_edit_t (id) values (1)"); r.Editable != nil || r.ReadOnlyReason != nil { + t.Fatalf("insert: %+v", r) + } + + // Synonyms and views, when the test user may create them. + if tryRun(s, "create or replace synonym lq_edit_syn for lq_edit_t") { + if tb := targetOf(t, run(t, s, "select * from lq_edit_syn")).Table; tb != "LQ_EDIT_T" { + t.Fatalf("synonym: %s", tb) + } + tryRun(s, "drop synonym lq_edit_syn") + } + if tryRun(s, "create or replace view lq_edit_v as select * from lq_edit_t") { + if r := reasonOf(t, run(t, s, "select * from lq_edit_v")); !strings.Contains(r, "view") { + t.Fatal(r) + } + tryRun(s, "drop view lq_edit_v") + } +} + +func TestOracleEditRoundTripTypes(t *testing.T) { + s := oraSession(t) + tryRun(s, "drop table lq_edit_types purge") + run(t, s, `create table lq_edit_types ( + id number(10) primary key, n number(20,5), big number, i number(10), + f binary_float, d binary_double, dt date, ts timestamp(6), ts9 timestamp(9), + tz timestamp(3) with time zone, c varchar2(100), ch char(5), nc nvarchar2(20), + cl clob, r raw(16), bl blob)`) + t.Cleanup(func() { tryRun(s, "drop table lq_edit_types purge") }) + run(t, s, `insert into lq_edit_types (id, n, big, i, f, d, dt, ts, ts9, tz, c, ch, nc, cl, r, bl) + values (10, 12345.678, 1e30, 1000, 1.5, 0.1, timestamp '2024-02-29 13:45:10', + timestamp '2024-02-29 13:45:10.123456', timestamp '2024-02-29 13:45:10.123456789', + timestamp '2024-02-29 13:45:10.250 -03:00', 'it''s' || chr(10) || 'two "lines"', + 'ab', 'olá', to_clob('long text' || chr(10) || 'x'), hextoraw('DEADBEEF'), + hextoraw('00FF10'))`) + run(t, s, "insert into lq_edit_types (id) values (20)") + run(t, s, "insert into lq_edit_types (id, n, f) values (7, -0.5, -2.25)") + + sql := "select * from lq_edit_types order by id" + before := run(t, s, sql) + tg := targetOf(t, before) + if !reflect.DeepEqual(tg.Key, []int{0}) { + t.Fatalf("key: %v", tg.Key) + } + for i, c := range tg.Columns { + if c == nil { + t.Fatalf("column %d is read-only", i) + } + } + row10 := before.Rows[1] + for i, w := range map[int]string{0: "10", 2: "1" + strings.Repeat("0", 30), 6: "2024-02-29 13:45:10", + 9: "2024-02-29 13:45:10.250 -03:00", 11: "ab "} { + if got := text(row10[i]); got != w { + t.Errorf("column %d: got %q, want %q", i, got, w) + } + } + + // Every column written back with its own displayed text. + var changes []model.RowChange + for _, row := range before.Rows { + var values []model.CellValue + for i := 1; i < len(row); i++ { + values = append(values, cv(i, row[i])) + } + changes = append(changes, model.RowChange{Op: model.OpUpdate, Key: []*string{row[0]}, Values: values}) + } + res, err := apply(s, tg, changes...) + if err != nil || res.Updated != 3 || res.InTransaction { + t.Fatalf("write back: %+v %v", res, err) + } + after := run(t, s, sql) + if !reflect.DeepEqual(after.Rows, before.Rows) { + t.Fatalf("values changed:\n%v\n%v", texts(before.Rows), texts(after.Rows)) + } + + // New values in the display format. + res, err = apply(s, tg, model.RowChange{Op: model.OpUpdate, Key: []*string{model.Str("10")}, Values: []model.CellValue{ + cv(1, model.Str("-0.00001")), + cv(4, model.Str("Inf")), + cv(5, model.Str("-1.25")), + cv(6, model.Str("2023-01-02 03:04:05")), + cv(7, model.Str("2023-01-02 03:04:05.000001")), + cv(9, model.Str("2023-01-02 03:04:05.5 +05:30")), + cv(10, model.Str(`x'y"z`)), + cv(12, nil), + cv(14, model.Str("0a0b")), + }}) + if err != nil || res.Updated != 1 { + t.Fatalf("update: %+v %v", res, err) + } + row := run(t, s, "select * from lq_edit_types where id = 10").Rows[0] + for i, w := range map[int]string{1: "-0.00001", 4: "Inf", 5: "-1.25", 6: "2023-01-02 03:04:05", + 7: "2023-01-02 03:04:05.000001", 9: "2023-01-02 03:04:05.500 +05:30", 10: `x'y"z`, 12: "NULL", 14: "0A0B"} { + if got := text(row[i]); got != w { + t.Errorf("column %d: got %q, want %q", i, got, w) + } + } + + // Insert a copy of a row under a new key, then delete it. + source := after.Rows[1] + var values []model.CellValue + for i := 1; i < len(source); i++ { + values = append(values, cv(i, source[i])) + } + values = append(values, cv(0, model.Str("30"))) + if res, err := apply(s, tg, model.RowChange{Op: model.OpInsert, Values: values}); err != nil || res.Inserted != 1 { + t.Fatalf("insert: %+v %v", res, err) + } + copied := run(t, s, "select * from lq_edit_types where id = 30").Rows[0] + if !reflect.DeepEqual(copied[1:], source[1:]) { + t.Fatalf("copy differs:\n%v\n%v", texts([]model.Row{copied}), texts([]model.Row{source})) + } + if res, err := apply(s, tg, model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("30")}}); err != nil || res.Deleted != 1 { + t.Fatalf("delete: %+v %v", res, err) + } + if n := len(run(t, s, "select * from lq_edit_types where id = 30").Rows); n != 0 { + t.Fatalf("%d rows left", n) + } +} + +func texts(rows []model.Row) [][]string { + out := make([][]string, len(rows)) + for i, r := range rows { + out[i] = make([]string, len(r)) + for j, v := range r { + out[i][j] = text(v) + } + } + return out +} + +func TestOracleEditDateKeysAndBooleans(t *testing.T) { + s := oraSession(t) + tryRun(s, "drop table lq_edit_dk purge") + run(t, s, "create table lq_edit_dk (d date, ts timestamp(6), v varchar2(10), primary key (d, ts))") + t.Cleanup(func() { tryRun(s, "drop table lq_edit_dk purge") }) + run(t, s, "insert into lq_edit_dk values (timestamp '2024-01-02 03:04:05', timestamp '2024-01-02 03:04:05.000007', 'a')") + r := run(t, s, "select v, d, ts from lq_edit_dk") + tg := targetOf(t, r) + if !reflect.DeepEqual(tg.Key, []int{1, 2}) { + t.Fatalf("key: %v", tg.Key) + } + res, err := apply(s, tg, model.RowChange{Op: model.OpUpdate, Key: []*string{r.Rows[0][1], r.Rows[0][2]}, + Values: []model.CellValue{cv(0, model.Str("b"))}}) + if err != nil || res.Updated != 1 { + t.Fatalf("update by date key: %+v %v", res, err) + } + run(t, s, "drop table lq_edit_dk purge") + + // BOOLEAN columns exist from 23ai on. + tryRun(s, "drop table lq_edit_bool purge") + if !tryRun(s, "create table lq_edit_bool (id number primary key, b boolean)") { + return + } + t.Cleanup(func() { tryRun(s, "drop table lq_edit_bool purge") }) + run(t, s, "insert into lq_edit_bool values (1, true)") + r = run(t, s, "select * from lq_edit_bool") + tg = targetOf(t, r) + if got := text(r.Rows[0][1]); got != "TRUE" || r.Columns[1].Kind != model.KindBool { + t.Fatalf("boolean: %q %s", got, r.Columns[1].Kind) + } + if _, err := apply(s, tg, model.RowChange{Op: model.OpUpdate, Key: []*string{model.Str("1")}, + Values: []model.CellValue{cv(1, model.Str("FALSE"))}}); err != nil { + t.Fatal(err) + } + if got := oneRow(t, s, "select b from lq_edit_bool")[0]; got != "FALSE" { + t.Fatalf("after update: %q", got) + } +} + +func TestOracleEditTransactions(t *testing.T) { + s := oraSession(t) + p, pw := oraProfile(t) + other := open(t, p, pw) + tryRun(s, "drop table lq_edit_tx purge") + run(t, s, "create table lq_edit_tx (id number primary key, v varchar2(10))") + t.Cleanup(func() { tryRun(s, "drop table lq_edit_tx purge") }) + run(t, s, "insert into lq_edit_tx values (1, 'a')") + run(t, s, "insert into lq_edit_tx values (2, 'b')") + tg := targetOf(t, run(t, s, "select id, v from lq_edit_tx")) + set := func(id, v string) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: []*string{model.Str(id)}, Values: []model.CellValue{cv(1, model.Str(v))}} + } + values := func(s *Session) []string { return firstColumn(run(t, s, "select v from lq_edit_tx order by id").Rows) } + + // A key that matches nothing undoes the whole batch. + _, err := apply(s, tg, set("1", "x"), set("99", "y")) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || !strings.HasPrefix(e.Message, "Row 2 was not saved: 0 rows") { + t.Fatalf("got %v", err) + } + if got := values(s); !reflect.DeepEqual(got, []string{"a", "b"}) || s.TxState().InTransaction { + t.Fatalf("after failure: %v", got) + } + + // Autocommit: other sessions see the change at once. + if res, err := apply(s, tg, set("1", "x")); err != nil || res.InTransaction { + t.Fatalf("%+v %v", res, err) + } + if got := values(other); !reflect.DeepEqual(got, []string{"x", "b"}) { + t.Fatalf("other: %v", got) + } + + // Manual mode: the change joins the open transaction. + if _, err := s.SetAutocommit(context.Background(), false); err != nil { + t.Fatal(err) + } + if res, err := apply(s, tg, set("2", "z")); err != nil || !res.InTransaction || !s.TxState().InTransaction { + t.Fatalf("%+v %v", res, err) + } + if got := values(s); !reflect.DeepEqual(got, []string{"x", "z"}) { + t.Fatalf("own: %v", got) + } + if got := values(other); !reflect.DeepEqual(got, []string{"x", "b"}) { + t.Fatalf("other: %v", got) + } + if _, err := s.EndTransaction(context.Background(), false); err != nil { + t.Fatal(err) + } + if got := values(s); !reflect.DeepEqual(got, []string{"x", "b"}) { + t.Fatalf("after rollback: %v", got) + } + + // A failure in manual mode keeps the earlier work of the transaction. + run(t, s, "update lq_edit_tx set v = 'm' where id = 1") + _, err = apply(s, tg, set("2", "q"), model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("99")}}) + if err == nil || !strings.HasPrefix(apperr.From(err).Message, "Row 2") { + t.Fatalf("got %v", err) + } + if !s.TxState().InTransaction { + t.Fatal("transaction closed") + } + if got := values(s); !reflect.DeepEqual(got, []string{"m", "b"}) { + t.Fatalf("after failure: %v", got) + } + if _, err := s.EndTransaction(context.Background(), false); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(context.Background(), true); err != nil { + t.Fatal(err) + } + + // Bad input is refused before anything runs. + _, err = apply(s, tg, model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("abc")}}) + if apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("got %v", err) + } + if got := values(s); !reflect.DeepEqual(got, []string{"x", "b"}) { + t.Fatalf("after bad input: %v", got) + } +} + +func TestOracleEditQuotedNames(t *testing.T) { + s := oraSession(t) + tryRun(s, `drop table "lq_edit Mixed" purge`) + run(t, s, `create table "lq_edit Mixed" ("Id Key" number primary key, "Some Value" varchar2(20), "lower" date)`) + t.Cleanup(func() { tryRun(s, `drop table "lq_edit Mixed" purge`) }) + run(t, s, `insert into "lq_edit Mixed" values (1, 'one', date '2024-01-01')`) + + tg := targetOf(t, run(t, s, `select m."Some Value" sv, m."Id Key", "lower" from "lq_edit Mixed" m`)) + if tg.Table != "lq_edit Mixed" || !reflect.DeepEqual(tg.Key, []int{1}) || tg.Columns[0].Name != "Some Value" { + t.Fatalf("target: %+v", tg) + } + res, err := apply(s, tg, + model.RowChange{Op: model.OpUpdate, Key: []*string{model.Str("1")}, + Values: []model.CellValue{cv(0, model.Str("uno")), cv(2, model.Str("2024-12-31 23:59:59"))}}, + model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cv(1, model.Str("2")), cv(0, model.Str("two"))}}) + if err != nil || res.Updated != 1 || res.Inserted != 1 { + t.Fatalf("%+v %v", res, err) + } + r := run(t, s, `select "Id Key", "Some Value", "lower" from "lq_edit Mixed" order by 1`) + got := texts(r.Rows) + if got[0][1] != "uno" || got[0][2] != "2024-12-31 23:59:59" || got[1][1] != "two" { + t.Fatalf("rows: %v", got) + } + if res, err := apply(s, targetOf(t, r), model.RowChange{Op: model.OpDelete, Key: []*string{model.Str("2")}}); err != nil || res.Deleted != 1 { + t.Fatalf("%+v %v", res, err) + } +} + +func TestOracleClosedSession(t *testing.T) { + s := oraSession(t) + if err := s.Close(); err != nil { + t.Fatal(err) + } + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "select 1 from dual"}) + if e := apperr.From(err); e == nil || e.Kind != apperr.Connection { + t.Fatalf("got %v", err) + } + if !errors.Is(s.Close(), nil) { + t.Fatal("second close failed") + } +} diff --git a/internal/drivers/oracle/oracle.go b/internal/drivers/oracle/oracle.go new file mode 100644 index 0000000..1c2f903 --- /dev/null +++ b/internal/drivers/oracle/oracle.go @@ -0,0 +1,1258 @@ +// Package oracle is the Oracle session over go-ora, a pure Go implementation +// of the Oracle network protocol: no Oracle Client or Instant Client needs to +// be installed. +// +// - The row limit is applied by sizing the fetch from it and closing the +// cursor at the limit, without fetching the rest from the server. +// - SQL statements lose their trailing `;`, PL/SQL keeps it, and a `/` on +// its own line ends a block, as in SQL*Plus. +// - DBMS_OUTPUT is enabled when the session opens and read after each +// statement that is not a query. +// - Cancel sends a break to the server, which stops the running statement +// or fetch with ORA-01013; the session stays usable. +// - go-ora never commits on its own: the session commits after DML and +// PL/SQL when autocommit is on. +// - TNS aliases are resolved by tns.go (TNS_ADMIN, ORACLE_HOME, the Windows +// registry, clients on PATH; Latin-1 files, IFILE, NAMES.DEFAULT_DOMAIN) +// and the driver receives the full descriptor. +package oracle + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode" + "unicode/utf8" + + goora "github.com/sijms/go-ora/v2" + "github.com/sijms/go-ora/v2/configurations" + "github.com/sijms/go-ora/v2/network" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + maxOutputLines = 5000 + closedMessage = "The connection to the server was closed." + // fetchArray is the most rows fetched per round trip by Execute. + fetchArray = 1000 +) + +// Session is one Oracle connection. +type Session struct { + // mu serializes every call except Cancel. + mu sync.Mutex + conn *goora.Connection + // live mirrors conn for Close, which may not get mu while a call hangs. + live atomic.Pointer[goora.Connection] + // dial opens a new connection with the same settings (see reopen). + dial func(ctx context.Context) (*goora.Connection, error) + + runMu sync.Mutex + cancelRun context.CancelFunc + + stateMu sync.Mutex + state model.TxState + + // Dictionary lookups for editable results, per table as written. + tables map[tableKey]lookup + + serverVersion string + currentUser *string + currentSchema *string +} + +type tableKey struct { + schema string + hasSchema bool + table string +} + +var _ drivers.Session = (*Session)(nil) + +// Connect opens a session. password nil means none. +func Connect(ctx context.Context, p model.ConnectionProfile, password *string) (*Session, error) { + descriptor, err := networkTarget(p) + if err != nil { + return nil, err + } + pw := "" + if password != nil { + pw = *password + } + user := strings.TrimSpace(p.User) + privilege := strings.ToLower(strings.TrimSpace(string(p.OraclePrivilege))) + s := &Session{ + state: model.TxState{Autocommit: true}, + tables: map[tableKey]lookup{}, + dial: func(ctx context.Context) (*goora.Connection, error) { + return dial(ctx, user, pw, descriptor, privilege) + }, + } + conn, err := s.dial(ctx) + if err != nil { + return nil, err + } + s.setConn(conn) + rows, err := textRows(ctx, conn, + "select sys_context('USERENV', 'SESSION_USER'), sys_context('USERENV', 'CURRENT_SCHEMA') from dual") + if err == nil && len(rows) == 0 { + err = apperr.Internalf("The server did not report the session user.") + } + if err != nil { + _ = conn.Close() + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + return nil, err + } + s.serverVersion = "Oracle " + versionText(conn.SessionProperties["AUTH_VERSION_NO"]) + if rows[0][0] != "" { + s.currentUser = model.Str(rows[0][0]) + } + if rows[0][1] != "" { + s.currentSchema = model.Str(rows[0][1]) + } + return s, nil +} + +// versionText formats AUTH_VERSION_NO as the Oracle drivers do (23.5.0.24.7). +func versionText(raw string) string { + n, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 32) + if err != nil { + return strings.TrimSpace(raw) + } + if n>>24&0xff >= 18 { + return fmt.Sprintf("%d.%d.%d.%d.%d", n>>24&0xff, n>>16&0xff, n>>12&0x0f, n>>4&0xff, n&0x0f) + } + return fmt.Sprintf("%d.%d.%d.%d.%d", n>>24&0xff, n>>20&0x0f, n>>12&0x0f, n>>8&0x0f, n&0x0f) +} + +// connectString builds the address of service and SID profiles as full +// descriptors, so they do not depend on name resolution. +func connectString(p model.ConnectionProfile) string { + host := strings.TrimSpace(p.Host) + port := p.Port + if port == 0 { + port = 1521 + } + target := strings.TrimSpace(p.Database) + switch p.OracleConnectType { + case model.OracleSID: + return fmt.Sprintf("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d))(CONNECT_DATA=(SID=%s)))", host, port, target) + case model.OracleTNS: + return strings.TrimSpace(p.TnsAlias) + case model.OracleCustom: + return strings.TrimSpace(p.ConnectString) + } + return fmt.Sprintf("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=%d))(CONNECT_DATA=(SERVICE_NAME=%s)))", host, port, target) +} + +// networkTarget returns the descriptor the driver connects with. TNS aliases +// (and bare names typed as a custom connect string) are resolved here; +// Easy Connect strings become descriptors. +func networkTarget(p model.ConnectionProfile) (string, error) { + ownDir := "" + if p.ConfigDir != nil { + ownDir = strings.TrimSpace(*p.ConfigDir) + } + switch p.OracleConnectType { + case model.OracleTNS: + descriptor, _, err := ResolveTNS(p.TnsAlias, ownDir) + return descriptor, err + case model.OracleCustom: + target := connectString(p) + switch { + case target == "": + return "", apperr.Invalidf("Enter the connect string.") + case strings.HasPrefix(target, "("): + return target, nil + case !strings.ContainsAny(target, "(/:@ "): + // A bare name is an alias. + descriptor, _, err := ResolveTNS(target, ownDir) + return descriptor, err + } + return easyConnect(target) + } + return connectString(p), nil +} + +// easyConnect turns `[protocol://][//]host[:port][/service[:server][/instance]][?...]` +// into a descriptor. +func easyConnect(text string) (string, error) { + invalid := apperr.Invalidf("The connect string %q is not a descriptor or an Easy Connect string (host:port/service).", text) + rest := text + protocol := "TCP" + if i := strings.Index(rest, "://"); i >= 0 { + protocol = strings.ToUpper(rest[:i]) + rest = rest[i+3:] + } + if protocol != "TCP" && protocol != "TCPS" { + return "", invalid + } + rest = strings.TrimPrefix(rest, "//") + if i := strings.IndexByte(rest, '?'); i >= 0 { + rest = rest[:i] + } + var host string + if strings.HasPrefix(rest, "[") { + end := strings.IndexByte(rest, ']') + if end < 0 { + return "", invalid + } + host, rest = rest[1:end], rest[end+1:] + } else if i := strings.IndexAny(rest, ":/"); i >= 0 { + host, rest = rest[:i], rest[i:] + } else { + host, rest = rest, "" + } + port := "1521" + if r, ok := strings.CutPrefix(rest, ":"); ok { + port, rest = r, "" + if i := strings.IndexByte(r, '/'); i >= 0 { + port, rest = r[:i], r[i:] + } + if _, err := strconv.ParseUint(port, 10, 16); err != nil { + return "", invalid + } + } + var service, server, instance string + if r, ok := strings.CutPrefix(rest, "/"); ok { + service = r + if i := strings.IndexByte(service, '/'); i >= 0 { + service, instance = service[:i], service[i+1:] + } + if i := strings.IndexByte(service, ':'); i >= 0 { + service, server = service[:i], service[i+1:] + } + } else if rest != "" { + return "", invalid + } + host, service = strings.TrimSpace(host), strings.TrimSpace(service) + if host == "" || strings.ContainsFunc(host, unicode.IsSpace) { + return "", invalid + } + if service == "" { + return "", apperr.Invalidf("Add the service name to the connect string (host:port/service).") + } + data := "(SERVICE_NAME=" + service + ")" + if server != "" { + data += "(SERVER=" + strings.ToUpper(server) + ")" + } + if instance != "" { + data += "(INSTANCE_NAME=" + instance + ")" + } + return fmt.Sprintf("(DESCRIPTION=(ADDRESS=(PROTOCOL=%s)(HOST=%s)(PORT=%s))(CONNECT_DATA=%s))", protocol, host, port, data), nil +} + +// dial opens a connection and prepares the session (module name, +// DBMS_OUTPUT, no automatic commits). +func dial(ctx context.Context, user, password, descriptor, privilege string) (*goora.Connection, error) { + cfg, err := goora.ParseConfig(goora.BuildUrl("localhost", 1521, "lowquery", user, password, nil)) + if err != nil { + return nil, apperr.Connectionf("The connection settings are not valid: %v.", err) + } + cfg.ServiceName, cfg.SID = "", "" + if err := cfg.UpdateDatabaseInfo(descriptor); err != nil { + return nil, apperr.Connectionf("The connect descriptor is not valid: %v.", err) + } + if cfg.ServiceName == "" && cfg.SID == "" { + return nil, apperr.Connectionf("The connect descriptor has no SERVICE_NAME or SID.") + } + if privilege != "" && privilege != "none" { + cfg.DBAPrivilege = configurations.DBAPrivilegeFromString(privilege) + } + cfg.ProgramName = "LowQuery" + cfg.ConnectTimeout = 15 * time.Second + cfg.Lob = configurations.INLINE + + conn, err := goora.NewConnection("", cfg) + if err != nil { + return nil, apperr.Connectionf("%v", err) + } + if err := conn.OpenWithContext(ctx); err != nil { + _ = conn.Close() + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + return nil, connectionError(err) + } + // go-ora commits after DML and PL/SQL until a transaction begins. + _, _ = conn.Begin() + if _, err := conn.ExecContext(ctx, + "begin dbms_application_info.set_module('LowQuery', null); dbms_output.enable(null); end;", nil); err != nil { + _ = conn.Close() + return nil, mapError(err) + } + return conn, nil +} + +func (s *Session) setConn(conn *goora.Connection) { + s.conn = conn + s.live.Store(conn) +} + +func (s *Session) Engine() model.Engine { return model.Oracle } +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) 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() +} + +// begin locks the session for one call and makes Cancel interrupt it. +func (s *Session) begin(ctx context.Context) (context.Context, func(), error) { + s.mu.Lock() + if s.conn == nil { + s.mu.Unlock() + return nil, nil, apperr.New(apperr.Connection, closedMessage) + } + runCtx, cancel := context.WithCancel(ctx) + s.runMu.Lock() + s.cancelRun = cancel + s.runMu.Unlock() + return runCtx, func() { + s.runMu.Lock() + s.cancelRun = nil + s.runMu.Unlock() + cancel() + s.mu.Unlock() + }, nil +} + +// run calls f on the connection. When the driver loses track of the +// server's reply, the connection is replaced. +func (s *Session) run(ctx context.Context, f func(conn *goora.Connection) error) error { + err := f(s.conn) + if err == nil { + return nil + } + e := apperr.From(err) + if ctx.Err() != nil { + if s.conn.State != goora.Opened || e.Kind == apperr.Internal { + _ = s.reopen(e) + } + if e.Kind == apperr.Cancelled { + return e + } + return apperr.CancelledErr() + } + if e.Kind == apperr.Internal { + return s.reopen(e) + } + return e +} + +// reopen moves the session to a new connection after a protocol error: the +// rest of the reply is still unread on the socket and every later call would +// fail on it. The open transaction is lost with the old connection. +func (s *Session) reopen(cause *apperr.Error) error { + s.stateMu.Lock() + wasInTransaction := s.state.InTransaction + s.state.InTransaction = false + s.stateMu.Unlock() + clear(s.tables) + disconnect(s.conn) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + conn, err := s.dial(ctx) + if err != nil { + e := apperr.Connectionf("The Oracle driver could not read the server's reply, and reconnecting failed: %s", + apperr.From(err).Message) + e.Detail = cause.Message + return e + } + s.setConn(conn) + msg := "The Oracle driver could not read the server's reply, so LowQuery reopened the connection." + if wasInTransaction { + msg += " The open transaction was rolled back." + } + e := apperr.New(apperr.Database, msg) + e.Detail = cause.Message + return e +} + +func connectionError(err error) *apperr.Error { + var oe *network.OracleError + if errors.As(err, &oe) { + e := mapError(err) + e.Kind = apperr.Connection + return e + } + return apperr.Connectionf("%s", capitalize(err.Error())) +} + +func capitalize(s string) string { + r, size := utf8.DecodeRuneInString(s) + if size == 0 { + return s + } + return string(unicode.ToUpper(r)) + s[size:] +} + +// mapError converts a go-ora error: ORA-NNNNN errors keep their code and +// position, a lost connection says so, and anything else means the driver +// could not follow the server's reply (kind internal, see reopen). +func mapError(err error) *apperr.Error { + if err == nil { + return nil + } + var ae *apperr.Error + if errors.As(err, &ae) { + return ae + } + var oe *network.OracleError + if errors.As(err, &oe) { + code := fmt.Sprintf("ORA-%05d", oe.ErrCode) + msg := oe.ErrMsg + if msg == "" { + msg = oe.Error() + } + msg = strings.TrimPrefix(msg, code+": ") + msg = strings.TrimRightFunc(msg, unicode.IsSpace) + e := apperr.New(apperr.Database, msg) + // 1013: "user requested cancel of current operation". + if oe.ErrCode == 1013 { + e.Kind = apperr.Cancelled + } + if pos := oe.ErrPos(); pos > 0 { + e.Position = &pos + } + e.Code = code + return e + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || + errors.Is(err, network.ErrConnReset) { + return apperr.CancelledErr() + } + var ne net.Error + if errors.Is(err, driver.ErrBadConn) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || + errors.As(err, &ne) { + return apperr.New(apperr.Connection, closedMessage) + } + return apperr.Internalf("%s", capitalize(err.Error())) +} + +func positional(args []any) []driver.NamedValue { + out := make([]driver.NamedValue, len(args)) + for i, a := range args { + out[i] = driver.NamedValue{Ordinal: i + 1, Value: a} + } + return out +} + +// openQuery runs a query and returns its cursor and columns. +func openQuery(ctx context.Context, conn *goora.Connection, sql string, prefetch int, args ...any) (*goora.DataSet, []column, error) { + setPrefetch(conn, prefetch) + rows, err := conn.QueryContext(ctx, sql, positional(args)) + if err != nil { + return nil, nil, mapError(err) + } + ds, ok := rows.(*goora.DataSet) + if !ok || ds == nil { + if rows != nil { + _ = rows.Close() + } + return nil, nil, apperr.Internalf("The Oracle driver returned an unexpected result (%T).", rows) + } + params := describe(ds) + names := ds.Columns() + cols := make([]column, len(names)) + for i, name := range names { + if i < len(params) { + cols[i] = columnOf(¶ms[i]) + } else { + cols[i] = column{name: name} + } + } + return ds, cols, nil +} + +// next reads the next row; io.EOF at the end. ctx interrupts the fetch. +func next(ctx context.Context, conn *goora.Connection, ds *goora.DataSet, dest []driver.Value) error { + stop := watch(ctx, conn) + err := ds.Next(dest) + stop() + if err != nil { + if errors.Is(err, io.EOF) { + return io.EOF + } + return mapError(err) + } + return ctx.Err() +} + +// textRows runs a query and returns its values as text, NULL as "". +func textRows(ctx context.Context, conn *goora.Connection, sql string, args ...any) ([][]string, error) { + ds, cols, err := openQuery(ctx, conn, sql, 500, args...) + if err != nil { + return nil, err + } + defer ds.Close() + var out [][]string + dest := make([]driver.Value, len(cols)) + for { + if err := next(ctx, conn, ds, dest); err != nil { + if errors.Is(err, io.EOF) { + return out, nil + } + return nil, mapError(err) + } + row := make([]string, len(cols)) + for i, c := range cols { + if v := formatValue(ctx, c, dest[i]); v != nil { + row[i] = *v + } + } + out = append(out, row) + } +} + +// firstTexts returns the first column of every row, as text. +func firstTexts(ctx context.Context, conn *goora.Connection, sql string, args ...any) ([]string, error) { + rows, err := textRows(ctx, conn, sql, args...) + if err != nil { + return nil, err + } + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r[0] + } + return out, nil +} + +func execSQL(ctx context.Context, conn *goora.Connection, sql string, args ...any) (int64, error) { + res, err := conn.ExecContext(ctx, sql, positional(args)) + if err != nil { + return 0, mapError(err) + } + n, _ := res.RowsAffected() + return n, nil +} + +// endTx commits or rolls back. go-ora's transaction object does it with the +// protocol's own call and turns automatic commits back on, so they are +// turned off again. +func endTx(ctx context.Context, conn *goora.Connection, commit bool) error { + tx, err := conn.BeginTx(ctx, driver.TxOptions{}) + if err != nil { + return mapError(err) + } + if commit { + err = tx.Commit() + } else { + err = tx.Rollback() + } + _, _ = conn.Begin() + if err != nil { + return mapError(err) + } + return nil +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + ctx, end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + sql := PrepareSQL(req.SQL) + var result *model.ExecResult + err = s.run(ctx, func(conn *goora.Connection) error { + var err error + result, err = s.execute(ctx, conn, sql, req.MaxRows) + return err + }) + if err != nil { + return nil, err + } + result.InTransaction = s.TxState().InTransaction + result.Normalize() + return result, nil +} + +func (s *Session) execute(ctx context.Context, conn *goora.Connection, sql string, maxRows int) (*model.ExecResult, error) { + started := time.Now() + result := &model.ExecResult{} + kind := classify(sql) + if kind == kindQuery { + prefetch := fetchArray + if maxRows > 0 && maxRows+1 < fetchArray { + prefetch = maxRows + 1 + } + ds, cols, err := openQuery(ctx, conn, sql, prefetch) + if err != nil { + return nil, err + } + result.Columns = columnInfos(cols) + dest := make([]driver.Value, len(cols)) + for { + err := next(ctx, conn, ds, dest) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + _ = ds.Close() + return nil, mapError(err) + } + if maxRows > 0 && len(result.Rows) == maxRows { + result.Truncated = true + break + } + row := make(model.Row, len(cols)) + for i, c := range cols { + row[i] = formatValue(ctx, c, dest[i]) + } + result.Rows = append(result.Rows, row) + } + _ = ds.Close() + names := make([]string, len(cols)) + for i, c := range cols { + names[i] = c.name + } + target, reason, tableCols := s.editTarget(ctx, conn, sql, names) + restoreBooleans(result, tableCols) + if target != nil { + result.Editable = target + } else { + result.ReadOnlyReason = &reason + } + } else { + if kind != kindDML { + // DDL, ALTER SESSION (current schema) or PL/SQL may change what a + // table name resolves to. + clear(s.tables) + } + affected, err := execSQL(ctx, conn, sql) + if err != nil { + return nil, err + } + if kind == kindDML { + n := uint64(affected) + result.RowsAffected = &n + } + kw := drivers.FirstKeywords(sql, 2) + first, second := "", "" + if len(kw) > 0 { + first = kw[0] + } + if len(kw) > 1 { + second = kw[1] + } + switch { + case (first == "COMMIT" || first == "ROLLBACK") && second != "TO": + s.setInTransaction(false) + case kind == kindDDL: + // DDL implicitly commits the transaction. + s.setInTransaction(false) + case kind == kindDML || kind == kindPLSQL: + if s.TxState().Autocommit { + if err := endTx(ctx, conn, true); err != nil { + return nil, err + } + s.setInTransaction(false) + } else { + s.setInTransaction(true) + } + } + result.Notices = readDBMSOutput(ctx, conn) + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + return result, nil +} + +// DBMS_OUTPUT is read in round trips of up to outputChunks out binds of +// outputChunkChars characters each: binds over 4000 bytes fail on servers +// with MAX_STRING_SIZE = STANDARD, and 1000 characters take at most 4000 +// bytes. +const ( + outputChunks = 16 + outputChunkChars = 1000 +) + +// dbmsOutputSQL reads pending DBMS_OUTPUT lines, each as its length in +// characters, a colon and the line (cut to 3900 bytes), while another line +// of the largest size still fits in the chunks. :1 is the status of the last +// GET_LINE (1 when no lines are left), :2 onwards the chunks. +var dbmsOutputSQL = func() string { + var b strings.Builder + limit := outputChunks*outputChunkChars - 3905 + fmt.Fprintf(&b, `declare + l varchar2(32767); + s integer := 0; + buf varchar2(32767); + n integer := 0; +begin + while n < 1000 and nvl(length(buf), 0) <= %d and nvl(lengthb(buf), 0) <= %d loop + dbms_output.get_line(l, s); + exit when s <> 0; + l := substrb(l, 1, 3900); + buf := buf || nvl(length(l), 0) || ':' || l; + n := n + 1; + end loop; + :1 := s; +`, limit, 32767-3905) + for i := 0; i < outputChunks; i++ { + fmt.Fprintf(&b, " :%d := substr(buf, %d, %d);\n", i+2, i*outputChunkChars+1, outputChunkChars) + } + b.WriteString("end;") + return b.String() +}() + +// readDBMSOutput returns the pending DBMS_OUTPUT lines. +func readDBMSOutput(ctx context.Context, conn *goora.Connection) []string { + lines := []string{} + chunks := make([]string, outputChunks) + for len(lines) < maxOutputLines { + var status int64 + args := []any{goora.Out{Dest: &status}} + for i := range chunks { + chunks[i] = "" + args = append(args, goora.Out{Dest: &chunks[i], Size: outputChunkChars}) + } + if _, err := conn.ExecContext(ctx, dbmsOutputSQL, positional(args)); err != nil { + break + } + lines = append(lines, splitOutput(strings.Join(chunks, ""))...) + if status != 0 { + break + } + } + if len(lines) > maxOutputLines { + lines = lines[:maxOutputLines] + } + return lines +} + +// splitOutput reads the `length:line` pieces of dbmsOutputSQL. +func splitOutput(buf string) []string { + var out []string + rest := []rune(buf) + for len(rest) > 0 { + i := 0 + for i < len(rest) && rest[i] >= '0' && rest[i] <= '9' { + i++ + } + if i == 0 || i >= len(rest) || rest[i] != ':' { + break + } + n, _ := strconv.Atoi(string(rest[:i])) + rest = rest[i+1:] + if n > len(rest) { + n = len(rest) + } + out = append(out, string(rest[:n])) + rest = rest[n:] + } + return out +} + +// editTarget works out whether the rows of a query can be edited, and how. +// It also returns the table column behind each result column, when the +// query reads one table. +func (s *Session) editTarget(ctx context.Context, conn *goora.Connection, sql string, names []string) (*model.EditTarget, string, []*tableColumn) { + shape, reason := parseSelect(sql) + if shape == nil { + return nil, reason, nil + } + if shape.table == "DUAL" && (shape.schema == nil || *shape.schema == "SYS") { + return nil, roTable, nil + } + key := tableKey{table: shape.table} + if shape.schema != nil { + key.schema, key.hasSchema = *shape.schema, true + } + l, ok := s.tables[key] + if !ok { + var schema any + if shape.schema != nil { + schema = *shape.schema + } + rows, err := textRows(ctx, conn, lookupSQL, schema, shape.table, schema, shape.table, shape.table) + if err != nil { + return nil, roUnknown, nil + } + l = buildTableInfo(shape.table, rows) + s.tables[key] = l + } + if l.table == nil { + return nil, l.readOnly, nil + } + target, reason := mapColumns(shape, l.table, names) + return target, reason, resultColumns(shape, l.table, names) +} + +// restoreBooleans shows BOOLEAN table columns as booleans. go-ora does not +// announce BOOLEAN support when it connects, so Oracle 23ai sends them as +// NUMBER 1/0; the table's own column types tell them apart. +func restoreBooleans(result *model.ExecResult, tableCols []*tableColumn) { + for i, tc := range tableCols { + if tc == nil || i >= len(result.Columns) || tc.typeName != "BOOLEAN" || + result.Columns[i].Kind != model.KindNumber { + continue + } + result.Columns[i].TypeName = "BOOLEAN" + result.Columns[i].Kind = model.KindBool + for _, row := range result.Rows { + if v := row[i]; v != nil { + b := "TRUE" + if *v == "0" { + b = "FALSE" + } + row[i] = &b + } + } + } +} + +func (s *Session) Cancel(ctx context.Context) error { + s.runMu.Lock() + cancel := s.cancelRun + s.runMu.Unlock() + if cancel != nil { + cancel() + } + return nil +} + +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + if on && s.TxState().InTransaction { + // Switching back to autocommit commits pending work, as JDBC + // clients do. + if _, err := s.EndTransaction(ctx, true); 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) { + ctx, end, err := s.begin(ctx) + if err != nil { + return s.TxState(), err + } + defer end() + err = s.run(ctx, func(conn *goora.Connection) error { return endTx(ctx, conn, commit) }) + if err != nil { + return s.TxState(), err + } + s.setInTransaction(false) + return s.TxState(), nil +} + +// metadata runs a dictionary query on the session. +func (s *Session) metadata(ctx context.Context, sql string, args ...any) ([][]string, error) { + ctx, end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + var rows [][]string + err = s.run(ctx, func(conn *goora.Connection) error { + var err error + rows, err = textRows(ctx, conn, sql, args...) + return err + }) + return rows, err +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + // Schemas with objects: the user's first, Oracle-maintained ones last. + // ORACLE_MAINTAINED only exists from 12c on. + rows, err := s.metadata(ctx, `select username from all_users u + where u.username = sys_context('USERENV', 'CURRENT_SCHEMA') + or exists (select 1 from all_objects o where o.owner = u.username) + order by case when username = sys_context('USERENV', 'CURRENT_SCHEMA') then 0 + when oracle_maintained = 'Y' then 2 else 1 end, username`) + if err != nil { + if k := apperr.From(err).Kind; k != apperr.Database { + return nil, err + } + rows, err = s.metadata(ctx, `select username from all_users u + where u.username = sys_context('USERENV', 'CURRENT_SCHEMA') + or exists (select 1 from all_objects o where o.owner = u.username) + order by case when username = sys_context('USERENV', 'CURRENT_SCHEMA') + then 0 else 1 end, username`) + if err != nil { + return nil, err + } + } + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r[0] + } + return out, nil +} + +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + rows, err := s.metadata(ctx, `select object_name, + case object_type when 'TABLE' then 'table' when 'VIEW' then 'view' + when 'MATERIALIZED VIEW' then 'matview' when 'SEQUENCE' then 'sequence' + when 'FUNCTION' then 'function' when 'PROCEDURE' then 'procedure' + when 'PACKAGE' then 'package' when 'TYPE' then 'type' + when 'SYNONYM' then 'synonym' end + from all_objects + where owner = :1 and object_type in ('TABLE','VIEW','MATERIALIZED VIEW','SEQUENCE', + 'FUNCTION','PROCEDURE','PACKAGE','TYPE','SYNONYM') + and object_name not like 'BIN$%' + and not (object_type = 'TABLE' and exists ( + select 1 from all_mviews m where m.owner = all_objects.owner + and m.mview_name = all_objects.object_name)) + 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: r[0], Kind: r[1]} + } + return out, nil +} + +// columnsSQL lists a table's columns. DATA_DEFAULT is a LONG, which SQL +// cannot trim or test; its VARCHAR2 copy DATA_DEFAULT_VC exists from 23ai +// on. Before that the LONG itself is read, with IDENTITY_COLUMN (12c on) to +// leave out identity sequences; servers older still list no defaults. +func columnsSQL(defaultExpr string) string { + return `select c.column_name, + case + when c.data_type in ('VARCHAR2','NVARCHAR2','CHAR','NCHAR','RAW') + then c.data_type || '(' || case when c.char_length > 0 then c.char_length else c.data_length end || ')' + when c.data_type = 'NUMBER' and c.data_precision is not null + then 'NUMBER(' || c.data_precision || + case when c.data_scale > 0 then ',' || c.data_scale end || ')' + else c.data_type end, + c.nullable, + case when exists ( + select 1 from all_constraints k + join all_cons_columns kc on kc.owner = k.owner + and kc.constraint_name = k.constraint_name + where k.owner = c.owner and k.table_name = c.table_name + and k.constraint_type = 'P' and kc.column_name = c.column_name) + then 'Y' else 'N' end, ` + defaultExpr + ` + from all_tab_columns c + where c.owner = :1 and c.table_name = :2 + order by c.column_id` +} + +func (s *Session) ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + var rows [][]string + var err error + for _, expr := range []string{ + "case when c.identity_column = 'YES' then null else trim(c.data_default_vc) end, null", + "c.data_default, c.identity_column", + "null, null", + } { + rows, err = s.metadata(ctx, columnsSQL(expr), schema, table) + if err == nil || apperr.From(err).Kind != apperr.Database { + break + } + } + if err != nil { + return nil, err + } + out := make([]model.DbColumn, len(rows)) + for i, r := range rows { + out[i] = model.DbColumn{ + Name: r[0], + TypeName: r[1], + Nullable: r[2] == "Y", + PrimaryKey: r[3] == "Y", + } + if d := strings.TrimSpace(r[4]); d != "" && r[5] != "YES" { + out[i].DefaultValue = model.Str(d) + } + } + return out, nil +} + +// ObjectDDL reads DDL from DBMS_METADATA, with a table's indexes (other than +// those behind its keys), triggers and comments; PL/SQL units come from +// their source. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + objectTypes := map[string]string{ + "table": "TABLE", "view": "VIEW", "matview": "MATERIALIZED_VIEW", "sequence": "SEQUENCE", + "function": "FUNCTION", "procedure": "PROCEDURE", "package": "PACKAGE", "type": "TYPE", + "synonym": "SYNONYM", + } + objectType, ok := objectTypes[kind] + if !ok { + return "", apperr.Invalidf("LowQuery cannot script a %s on Oracle.", kind) + } + ctx, end, err := s.begin(ctx) + if err != nil { + return "", err + } + defer end() + var out string + err = s.run(ctx, func(conn *goora.Connection) error { + var err error + switch kind { + case "function", "procedure", "package", "type": + out, err = unitSource(ctx, conn, schema, name, objectType) + default: + out, err = metadataDDL(ctx, conn, schema, name, objectType, kind == "table") + } + return err + }) + return out, err +} + +// unitSource returns a PL/SQL unit from its stored source, as SQL Developer +// shows it, spec and body together. +func unitSource(ctx context.Context, conn *goora.Connection, schema, name, objectType string) (string, error) { + var b strings.Builder + for _, unit := range []string{objectType, objectType + " BODY"} { + lines, err := firstTexts(ctx, conn, + "select text from all_source where owner = :1 and name = :2 and type = :3 order by line", + schema, name, unit) + if err != nil { + return "", err + } + if len(lines) == 0 { + continue + } + source := strings.TrimRightFunc(strings.Join(lines, ""), unicode.IsSpace) + b.WriteString("CREATE OR REPLACE " + source + "\n/\n\n") + } + return b.String(), nil +} + +func metadataDDL(ctx context.Context, conn *goora.Connection, schema, name, objectType string, table bool) (string, error) { + if _, err := execSQL(ctx, conn, `begin + dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'SQLTERMINATOR', true); + dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'PRETTY', true); + dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'STORAGE', false); + end;`); err != nil { + return "", err + } + defer func() { + _, _ = execSQL(context.Background(), conn, + "begin dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'DEFAULT'); end;") + }() + parts, err := firstTexts(ctx, conn, "select dbms_metadata.get_ddl(:1, :2, :3) from dual", objectType, name, schema) + if err != nil { + return "", err + } + if table { + for _, sql := range []string{ + `select dbms_metadata.get_ddl('INDEX', i.index_name, i.owner) + from all_indexes i + where i.table_owner = :1 and i.table_name = :2 and i.index_type <> 'LOB' + and not exists ( + select 1 from all_constraints k + where k.owner = i.table_owner and k.table_name = i.table_name + and k.index_name = i.index_name and k.constraint_type in ('P', 'U')) + order by i.index_name`, + `select dbms_metadata.get_ddl('TRIGGER', t.trigger_name, t.owner) + from all_triggers t + where t.table_owner = :1 and t.table_name = :2 + order by t.trigger_name`, + } { + more, err := firstTexts(ctx, conn, sql, schema, name) + if err != nil { + return "", err + } + parts = append(parts, more...) + } + // ORA-31608 when the table has no comments. + comments, err := firstTexts(ctx, conn, + "select dbms_metadata.get_dependent_ddl('COMMENT', :1, :2) from dual", name, schema) + if err == nil { + parts = append(parts, comments...) + } else if apperr.From(err).Kind != apperr.Database { + return "", err + } + } + kept := parts[:0] + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + kept = append(kept, p) + } + } + return strings.Join(kept, "\n\n") + "\n", nil +} + +func send(ctx context.Context, sink chan<- drivers.StreamEvent, ev drivers.StreamEvent) bool { + select { + case sink <- ev: + return true + case <-ctx.Done(): + return false + } +} + +// Stream reads the rows of a query from its cursor, in batches of +// StreamBatch. +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + ctx, end, err := s.begin(ctx) + if err != nil { + return 0, err + } + defer end() + ctx = drivers.WithFullValues(ctx) + sql = strings.TrimRight(strings.TrimSpace(sql), ";") + var total uint64 + err = s.run(ctx, func(conn *goora.Connection) error { + ds, cols, err := openQuery(ctx, conn, sql, drivers.StreamBatch) + if err != nil { + return err + } + defer ds.Close() + if !send(ctx, sink, drivers.StreamEvent{Columns: columnInfos(cols)}) { + return apperr.CancelledErr() + } + batch := make([]model.Row, 0, drivers.StreamBatch) + dest := make([]driver.Value, len(cols)) + for { + err := next(ctx, conn, ds, dest) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return mapError(err) + } + row := make(model.Row, len(cols)) + for i, c := range cols { + row[i] = formatValue(ctx, c, dest[i]) + } + batch = append(batch, row) + total++ + if len(batch) == drivers.StreamBatch { + if !send(ctx, sink, drivers.StreamEvent{Rows: batch}) { + return apperr.CancelledErr() + } + batch = make([]model.Row, 0, drivers.StreamBatch) + } + } + if len(batch) > 0 && !send(ctx, sink, drivers.StreamEvent{Rows: batch}) { + return apperr.CancelledErr() + } + return nil + }) + return total, err +} + +// ApplyChanges applies grid edits: with autocommit on they commit together +// or not at all; with autocommit off they join the open transaction behind a +// savepoint, so a failure undoes only them. +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + plan, err := planChanges(req) + if err != nil { + return nil, err + } + ctx, end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + started := time.Now() + out := &model.ApplyResult{} + err = s.run(ctx, func(conn *goora.Connection) error { + autocommit := s.TxState().Autocommit + if !autocommit { + if _, err := execSQL(ctx, conn, "savepoint lq_grid_apply"); err != nil { + return err + } + } + if err := runChanges(ctx, conn, plan, out); err != nil { + if autocommit { + _ = endTx(context.Background(), conn, false) + } else { + _, _ = execSQL(context.Background(), conn, "rollback to savepoint lq_grid_apply") + } + return err + } + if autocommit { + if err := endTx(ctx, conn, true); err != nil { + _ = endTx(context.Background(), conn, false) + return err + } + s.setInTransaction(false) + } else if len(plan) > 0 { + s.setInTransaction(true) + } + return nil + }) + if err != nil { + return nil, err + } + out.ElapsedMs = uint64(time.Since(started).Milliseconds()) + out.InTransaction = s.TxState().InTransaction + return out, nil +} + +func runChanges(ctx context.Context, conn *goora.Connection, plan []planned, out *model.ApplyResult) error { + for _, p := range plan { + affected, err := execSQL(ctx, conn, p.sql, p.binds...) + if err != nil { + e := *apperr.From(err) + // The position points into the generated statement, not the + // editor. + e.Position = nil + return &e + } + if affected != 1 { + return notSaved(p.row, affected) + } + switch p.op { + case opUpdate: + out.Updated++ + case opDelete: + out.Deleted++ + case opInsert: + out.Inserted++ + } + } + return nil +} + +// Close logs off; a running call is interrupted first. +func (s *Session) Close() error { + _ = s.Cancel(context.Background()) + locked := make(chan struct{}) + go func() { + s.mu.Lock() + close(locked) + }() + select { + case <-locked: + case <-time.After(10 * time.Second): + // The server does not answer the break: drop the socket. + if conn := s.live.Load(); conn != nil { + disconnect(conn) + } + <-locked + } + defer s.mu.Unlock() + if s.conn == nil { + return nil + } + conn := s.conn + s.conn = nil + s.live.Store(nil) + _ = conn.Close() + return nil +} diff --git a/internal/drivers/oracle/oracle_test.go b/internal/drivers/oracle/oracle_test.go new file mode 100644 index 0000000..4db8586 --- /dev/null +++ b/internal/drivers/oracle/oracle_test.go @@ -0,0 +1,865 @@ +package oracle + +import ( + "context" + "fmt" + "io" + "math" + "net" + "reflect" + "strconv" + "strings" + "testing" + "time" + + goora "github.com/sijms/go-ora/v2" + "github.com/sijms/go-ora/v2/network" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func TestPrepareSQLStripsTerminatorsOnlyForSQL(t *testing.T) { + for in, want := range map[string]string{ + "select 1 from dual;": "select 1 from dual", + "select 1 from dual\n/": "select 1 from dual", + "begin null; end;\n/": "begin null; end;", + "create or replace procedure p as begin null; end;": "create or replace procedure p as begin null; end;", + "select 10/2 from dual": "select 10/2 from dual", + "select 1 from dual ; ; \n": "select 1 from dual", + } { + if got := PrepareSQL(in); got != want { + t.Errorf("PrepareSQL(%q) = %q, want %q", in, got, want) + } + } +} + +func TestIsPLSQLDetectsUnits(t *testing.T) { + for _, sql := range []string{ + "DECLARE x number; BEGIN null; END;", + "create or replace editionable package body pkg as end;", + "CREATE TRIGGER t BEFORE INSERT ON x BEGIN NULL; END;", + "-- comment\nbegin null; end;", + } { + if !IsPLSQL(sql) { + t.Errorf("not PL/SQL: %q", sql) + } + } + for _, sql := range []string{"create table t (id number)", "create or replace view v as select 1 x from dual", ""} { + if IsPLSQL(sql) { + t.Errorf("PL/SQL: %q", sql) + } + } +} + +func TestClassify(t *testing.T) { + for sql, want := range map[string]statementKind{ + "(select 1 from dual)": kindQuery, + "with q as (select 1) x": kindQuery, + "merge into t using u": kindDML, + "call p()": kindPLSQL, + "truncate table t": kindDDL, + "alter session set x=1": kindDDL, + "commit": kindOther, + } { + if got := classify(sql); got != want { + t.Errorf("classify(%q) = %d, want %d", sql, got, want) + } + } +} + +// --- Editable results --- + +func str(s string) *string { return &s } + +func TestParseSelectSingleTable(t *testing.T) { + s, reason := parseSelect("select /*+ first_rows */ id, t.name, qty * 2 as dbl, q'[it's, from]' lit -- x\n from lq t where x = 'a, from' order by 1") + if s == nil { + t.Fatal(reason) + } + if s.schema != nil || s.table != "LQ" || s.alias == nil || *s.alias != "T" { + t.Fatalf("shape: %+v", s) + } + want := []selItem{ + {kind: selColumn, qual: []string{}, name: "ID"}, + {kind: selColumn, qual: []string{"T"}, name: "NAME"}, + {kind: selExpr}, + {kind: selExpr}, + } + if !itemsEqual(s.items, want) { + t.Fatalf("items: %+v", s.items) + } + + s, reason = parseSelect(`select m.*, "Some Col" as "x" from app."My Tab" m for update`) + if s == nil { + t.Fatal(reason) + } + if s.schema == nil || *s.schema != "APP" || s.table != "My Tab" { + t.Fatalf("shape: %+v", s) + } + want = []selItem{ + {kind: selStar, qual: []string{"M"}}, + {kind: selColumn, qual: []string{}, name: "Some Col", alias: str("x")}, + } + if !itemsEqual(s.items, want) { + t.Fatalf("items: %+v", s.items) + } + + // A subquery in WHERE does not change where the rows come from. + if s, reason := parseSelect("select * from t where id in (select id from u group by id) fetch first 5 rows only"); s == nil { + t.Fatal(reason) + } +} + +func itemsEqual(a, b []selItem) bool { + if len(a) != len(b) { + return false + } + for i := range a { + x, y := a[i], b[i] + if x.kind != y.kind || x.name != y.name || len(x.qual) != len(y.qual) { + return false + } + for j := range x.qual { + if x.qual[j] != y.qual[j] { + return false + } + } + if (x.alias == nil) != (y.alias == nil) || (x.alias != nil && *x.alias != *y.alias) { + return false + } + } + return true +} + +func TestParseSelectRejectsOtherShapes(t *testing.T) { + cases := []struct{ sql, reason string }{ + {"select a.id from a join b on a.id = b.id", roJoin}, + {"select * from a, b", roJoin}, + {"select * from a left outer join b using (id)", roJoin}, + {"select * from (select 1 x from dual)", roTable}, + {"select * from table(f())", roTable}, + {"with q as (select 1 from dual) select * from q", roTable}, + {"select distinct x from t", roGrouped}, + {"select x, count(*) from t group by x", roGrouped}, + {"select x from t having count(*) > 1", roGrouped}, + {"select x from t union all select x from u", roSet}, + {"select x from t where a = 1 minus select x from u", roSet}, + {"select level from t connect by level < 3", roComplex}, + {"select * from t as of scn 1", roComplex}, + {"select * from t sample (10)", roComplex}, + {"select * from t pivot (sum(v) for k in (1))", roComplex}, + {"select * from t@remote", roRemote}, + {"update t set x = 1", roTable}, + {"select 'unclosed from t", roComplex}, + } + for _, c := range cases { + s, reason := parseSelect(c.sql) + if s != nil || reason != c.reason { + t.Errorf("%s: got %+v %q, want %q", c.sql, s, reason, c.reason) + } + } +} + +func tcol(name, typeName string) tableColumn { + return tableColumn{name: name, typeName: typeName, nullable: true} +} + +func sampleTable() *tableInfo { + gen := tcol("TOTAL", "NUMBER") + gen.generated = true + return &tableInfo{ + owner: "APP", + name: "ORDERS", + columns: []tableColumn{ + tcol("ID", "NUMBER(10)"), + tcol("NAME", "VARCHAR2(50)"), + gen, + tcol("SEEN", "TIMESTAMP(6) WITH LOCAL TIME ZONE"), + }, + key: []string{"ID"}, + primary: true, + } +} + +func mustParse(t *testing.T, sql string) *selectShape { + t.Helper() + s, reason := parseSelect(sql) + if s == nil { + t.Fatalf("%s: %s", sql, reason) + } + return s +} + +func TestMapColumnsToTheTable(t *testing.T) { + info := sampleTable() + tg, reason := mapColumns(mustParse(t, "select name, o.id, id + 1, total from orders o"), info, []string{"NAME", "ID", "ID+1", "TOTAL"}) + if tg == nil { + t.Fatal(reason) + } + if *tg.Schema != "APP" || tg.Table != "ORDERS" || !reflect.DeepEqual(tg.Key, []int{1}) { + t.Fatalf("target: %+v", tg) + } + if tg.Columns[0].Name != "NAME" || tg.Columns[1].TypeName != "NUMBER(10)" { + t.Fatalf("columns: %+v %+v", tg.Columns[0], tg.Columns[1]) + } + // Expression, virtual column. + if tg.Columns[2] != nil || tg.Columns[3] != nil { + t.Fatal("expression or virtual column is editable") + } + + star := mustParse(t, "select * from orders") + tg, reason = mapColumns(star, info, []string{"ID", "NAME", "TOTAL", "SEEN"}) + if tg == nil { + t.Fatal(reason) + } + // TIMESTAMP WITH LOCAL TIME ZONE stays read-only. + if !reflect.DeepEqual(tg.Key, []int{0}) || tg.Columns[3] != nil { + t.Fatalf("star: %+v", tg) + } + + // The result must line up with what the text says. + if tg, _ := mapColumns(star, info, []string{"ID", "NAME"}); tg != nil { + t.Fatal("short result mapped") + } + aliased := mustParse(t, "select id x from orders") + if tg, _ := mapColumns(aliased, info, []string{"ID"}); tg != nil { + t.Fatal("alias ignored") + } + if tg, reason := mapColumns(aliased, info, []string{"X"}); tg == nil { + t.Fatal(reason) + } + + _, reason = mapColumns(mustParse(t, "select name from orders"), info, []string{"NAME"}) + if reason != "Read-only: add the primary key columns (ID) to the query to edit rows." { + t.Fatalf("reason: %q", reason) + } + + // A qualifier that is not the table is not one of its columns. + tg, reason = mapColumns(mustParse(t, "select s.id, id from orders"), info, []string{"ID", "ID"}) + if tg == nil { + t.Fatal(reason) + } + if tg.Columns[0] != nil || !reflect.DeepEqual(tg.Key, []int{1}) { + t.Fatalf("qualifier: %+v", tg) + } +} + +func TestBuildTableInfoChoosesTheKey(t *testing.T) { + rows := [][]string{ + {"O", "TABLE", "APP", "T", "", ""}, + {"C", "B", "VARCHAR2(10)", "N", "NO", "2"}, + {"C", "A", "NUMBER", "Y", "NO", "1"}, + {"C", "C", "NUMBER", "N", "NO", "3"}, + {"K", "U", "T_A", "A", "", "1"}, + {"K", "U", "T_BC", "C", "", "2"}, + {"K", "U", "T_BC", "B", "", "1"}, + } + l := buildTableInfo("T", rows) + if l.table == nil { + t.Fatal(l.readOnly) + } + var names []string + for _, c := range l.table.columns { + names = append(names, c.name) + } + if !reflect.DeepEqual(names, []string{"A", "B", "C"}) { + t.Fatalf("columns: %v", names) + } + // T_A is on a nullable column. + if !reflect.DeepEqual(l.table.key, []string{"B", "C"}) || l.table.primary { + t.Fatalf("key: %v %v", l.table.key, l.table.primary) + } + + withPK := append(append([][]string{}, rows...), []string{"K", "P", "T_PK", "A", "", "1"}) + l = buildTableInfo("T", withPK) + if l.table == nil || !reflect.DeepEqual(l.table.key, []string{"A"}) || !l.table.primary { + t.Fatalf("primary key: %+v", l) + } + + if l := buildTableInfo("T", rows[:4]); l.table != nil || l.readOnly != "Read-only: table T has no primary key." { + t.Fatalf("no key: %+v", l) + } + if l := buildTableInfo("V", [][]string{{"O", "VIEW", "APP", "V", "", ""}}); l.table != nil || !strings.Contains(l.readOnly, "view") { + t.Fatalf("view: %+v", l) + } + if l := buildTableInfo("R", [][]string{{"O", "REMOTE", "APP", "R", "", ""}}); l.readOnly != roRemote { + t.Fatalf("remote: %+v", l) + } + if l := buildTableInfo("X", nil); l.table != nil || l.readOnly == "" { + t.Fatalf("missing: %+v", l) + } +} + +// Numbers are bound as digits and an exponent, which to_number reads +// whatever the session's NLS settings. +func TestParseNumberWithoutNLS(t *testing.T) { + for in, want := range map[string]string{ + "123.4500": "12345E-2", + "-0.001": "-1E-3", + ".5": "5E-1", + "+7": "7E0", + "0": "0", + "-0.0": "0", + "15": "15E0", + " 42 ": "42E0", + "12345678901234567890.123456789": "12345678901234567890123456789E-9", + "100": "1E2", + "-1000": "-1E3", + "1" + strings.Repeat("0", 125): "1E125", + "0." + strings.Repeat("0", 120) + "1": "1E-121", + strings.Repeat("9", 40): strings.Repeat("9", 40) + "E0", + } { + got, ok := parseNumber(in) + if !ok || got != want { + t.Errorf("parseNumber(%q) = %q %v, want %q", in, got, ok, want) + } + } + for _, bad := range []string{"", "-", ".", "abc", "1e5", "1,5", "1.2.3", " ", "--1", strings.Repeat("9", 41)} { + if got, ok := parseNumber(bad); ok { + t.Errorf("parseNumber(%q) = %q", bad, got) + } + } +} + +func TestFloatText(t *testing.T) { + cases := []struct { + in string + bits int + special string + digits string + }{ + {"1.5", 64, "", "15E-1"}, + {"0.1", 64, "", "1E-1"}, + {"-2.25", 32, "", "-225E-2"}, + {"0", 64, "", "0E0"}, + {"1e300", 64, "", "1E300"}, + {"Inf", 64, "binary_double_infinity", ""}, + {"-Inf", 32, "-binary_float_infinity", ""}, + {"Nan", 64, "binary_double_nan", ""}, + {"1e400", 64, "binary_double_infinity", ""}, + } + for _, c := range cases { + special, digits, ok := floatText(c.in, c.bits) + if !ok || special != c.special || digits != c.digits { + t.Errorf("floatText(%q) = %q %q %v", c.in, special, digits, ok) + } + } + if _, _, ok := floatText("abc", 64); ok { + t.Error("abc accepted") + } +} + +func TestParseTimestampReadsDisplayedValues(t *testing.T) { + v, ok := parseTimestamp("2024-05-01 13:45:07") + if !ok || v != (timestampValue{year: 2024, month: 5, day: 1, hour: 13, minute: 45, second: 7}) { + t.Fatalf("got %+v %v", v, ok) + } + if v, _ := parseTimestamp("2024-05-01 13:45:07.123"); v.nanos != 123_000_000 { + t.Fatalf("nanos: %d", v.nanos) + } + v, _ = parseTimestamp("2024-05-01 13:45:07.123456789 -06:00") + if v.nanos != 123_456_789 || v.tz != "-06:00" { + t.Fatalf("tz: %+v", v) + } + if v, ok := parseTimestamp("2024-05-01"); !ok || v.hour != 0 || v.second != 0 { + t.Fatalf("date only: %+v", v) + } + if _, ok := parseTimestamp("2024-05-01T13:45:07"); !ok { + t.Fatal("T separator refused") + } + for _, bad := range []string{ + "2024-02-30 00:00:00", + "2024-05-01 24:00:00", + "2024-05-01 13:45", + "2024-05-01 13:45:07.", + "2024-05-01 13:45:07 +3", + "2024-05-01 13:45:07.1234567890", + "01/05/2024", + "", + } { + if v, ok := parseTimestamp(bad); ok { + t.Errorf("parseTimestamp(%q) = %+v", bad, v) + } + } + + // What formatTimestamp prints parses back to the same value. + ts := time.Date(1999, 12, 31, 23, 59, 58, 120_000_000, time.UTC) + shown := formatTimestamp(ts, 6, false) + if shown != "1999-12-31 23:59:58.120000" { + t.Fatalf("shown: %q", shown) + } + v, _ = parseTimestamp(shown) + if v.timestampText() != "1999-12-31 23:59:58.120000000" || v.dateText() != "1999-12-31 23:59:58" { + t.Fatalf("round trip: %+v", v) + } +} + +func TestFormatTimestampShowsTheOffset(t *testing.T) { + zone := func(h, m int) *time.Location { return time.FixedZone("", h*3600+m*60) } + cases := []struct { + t time.Time + digits int + want string + }{ + {time.Date(2025, 10, 31, 11, 52, 15, 456_000_000, zone(-6, 0)), 3, "2025-10-31 11:52:15.456 -06:00"}, + {time.Date(2023, 12, 31, 22, 30, 0, 0, zone(-3, -30)), 0, "2023-12-31 22:30:00 -03:30"}, + {time.Date(2024, 2, 29, 1, 30, 0, 0, zone(5, 30)), 0, "2024-02-29 01:30:00 +05:30"}, + {time.Date(2024, 2, 29, 1, 30, 0, 123_456_789, time.UTC), 9, "2024-02-29 01:30:00.123456789 +00:00"}, + } + for _, c := range cases { + if got := formatTimestamp(c.t, c.digits, true); got != c.want { + t.Errorf("got %q, want %q", got, c.want) + } + } +} + +func TestIntervals(t *testing.T) { + for in, want := range map[string]string{ + "+03 00:00:00.000000": "P3DT0H0M0.000000000S", + "+00 04:05:06.250000": "P0DT4H5M6.250000000S", + "-01 02:03:04.500000": "P-1DT-2H-3M-4.-500000000S", + "+1000 00:00:01.000001": "P1000DT0H0M1.000001000S", + } { + if got := intervalDS(in); got != want { + t.Errorf("intervalDS(%q) = %q, want %q", in, got, want) + } + } + for in, want := range map[string]string{"+01-02": "P1Y2M", "-01-02": "P-1Y-2M", "+00-00": "P0Y0M"} { + if got := intervalYM(in); got != want { + t.Errorf("intervalYM(%q) = %q, want %q", in, got, want) + } + } + if got := intervalDS("odd"); got != "odd" { + t.Errorf("unparsed interval: %q", got) + } +} + +func TestParseHexAndBool(t *testing.T) { + if b, ok := parseHex("DEADbeef"); !ok || !reflect.DeepEqual(b, []byte{0xDE, 0xAD, 0xBE, 0xEF}) { + t.Fatalf("hex: %v %v", b, ok) + } + if b, ok := parseHex(""); !ok || len(b) != 0 { + t.Fatal("empty hex") + } + for _, bad := range []string{"ABC", "ZZ", "+1"} { + if _, ok := parseHex(bad); ok { + t.Errorf("hex %q accepted", bad) + } + } + for in, want := range map[string]bool{"true": true, "FALSE": false, "1": true, " 0 ": false} { + if v, ok := parseBool(in); !ok || v != want { + t.Errorf("parseBool(%q) = %v %v", in, v, ok) + } + } + if _, ok := parseBool("yes"); ok { + t.Error("yes accepted") + } +} + +func TestColTypeOf(t *testing.T) { + for typeName, want := range map[string]colType{ + "NUMBER(10,2)": colNumber, + "FLOAT(126)": colNumber, + "BINARY_FLOAT": colBinaryFloat, + "BINARY_DOUBLE": colBinaryDouble, + "DATE": colDate, + "TIMESTAMP(6)": colTimestamp, + "TIMESTAMP(3) WITH TIME ZONE": colTimestampTZ, + "TIMESTAMP(6) WITH LOCAL TIME ZONE": colNone, + "VARCHAR2(20)": colText, + "NCLOB": colText, + "RAW(16)": colBinary, + "BLOB": colBinary, + "BOOLEAN": colBool, + "INTERVAL DAY(2) TO SECOND(6)": colNone, + "LONG": colNone, + "JSON": colNone, + "XMLTYPE": colNone, + } { + if got := colTypeOf(typeName); got != want { + t.Errorf("colTypeOf(%q) = %d, want %d", typeName, got, want) + } + } +} + +func ecol(name, typeName string) *model.EditColumn { + return &model.EditColumn{Name: name, TypeName: typeName} +} + +func sampleTarget() model.EditTarget { + return model.EditTarget{ + Schema: str("APP"), + Table: "My Tab", + Columns: []*model.EditColumn{ + ecol("ID", "NUMBER(10)"), + ecol("Some Value", "VARCHAR2(20)"), + nil, + ecol("D", "DATE"), + ecol("TZ", "TIMESTAMP(6) WITH TIME ZONE"), + ecol("BIN", "BLOB"), + ecol("F", "BINARY_DOUBLE"), + }, + Key: []int{0}, + } +} + +func cell(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func plan(changes ...model.RowChange) ([]planned, error) { + return planChanges(model.ApplyRequest{Target: sampleTarget(), Changes: changes}) +} + +func TestPlanChangesBuildsStatementsWithBinds(t *testing.T) { + p, err := plan( + model.RowChange{Op: model.OpUpdate, Key: []*string{str("10")}, + Values: []model.CellValue{cell(1, str("x")), cell(3, nil), cell(1, str("it's"))}}, + model.RowChange{Op: model.OpDelete, Key: []*string{nil}}, + model.RowChange{Op: model.OpInsert}, + model.RowChange{Op: model.OpInsert, Values: []model.CellValue{ + cell(3, str("2024-02-29 13:00:00")), + cell(4, str("2024-02-29 13:00:00.5 +03:00")), + cell(6, str("Inf")), + cell(5, str("00ff")), + }}, + model.RowChange{Op: model.OpUpdate, Key: []*string{str("7")}}, + model.RowChange{Op: model.OpUpdate, Key: []*string{str("8")}, Values: []model.CellValue{cell(6, str("-1.25"))}}, + ) + if err != nil { + t.Fatal(err) + } + if len(p) != 5 { + t.Fatalf("%d statements", len(p)) + } + check := func(i int, op changeOp, row int, sql string, binds ...any) { + t.Helper() + if p[i].op != op || p[i].row != row || p[i].sql != sql { + t.Errorf("statement %d: %v row %d\n%s\nwant\n%s", i, p[i].op, p[i].row, p[i].sql, sql) + } + if len(binds) == 0 && len(p[i].binds) == 0 { + return + } + if !reflect.DeepEqual(p[i].binds, binds) { + t.Errorf("statement %d binds: %#v, want %#v", i, p[i].binds, binds) + } + } + check(0, opUpdate, 1, `update "APP"."My Tab" set "Some Value" = :1, "D" = null where "ID" = to_number(:2)`, "it's", "1E1") + check(1, opDelete, 2, `delete from "APP"."My Tab" where "ID" is null`) + check(2, opInsert, 3, `insert into "APP"."My Tab" ("ID") values (default)`) + check(3, opInsert, 4, `insert into "APP"."My Tab" ("D", "TZ", "F", "BIN") values (to_date(:1, 'YYYY-MM-DD HH24:MI:SS'), `+ + `to_timestamp_tz(:2, 'YYYY-MM-DD HH24:MI:SS.FF9 TZH:TZM'), binary_double_infinity, :3)`, + "2024-02-29 13:00:00", "2024-02-29 13:00:00.500000000 +03:00", []byte{0x00, 0xFF}) + check(4, opUpdate, 6, `update "APP"."My Tab" set "F" = to_binary_double(:1) where "ID" = to_number(:2)`, "-125E-2", "8E0") +} + +func TestPlanChangesRejectsBadInput(t *testing.T) { + invalid := func(changes ...model.RowChange) string { + t.Helper() + _, err := plan(changes...) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Invalid { + t.Fatalf("got %v", err) + } + return e.Message + } + // Expression column. + invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(2, str("1"))}}) + if msg := invalid(model.RowChange{Op: model.OpDelete, Key: []*string{str("abc")}}); msg != "Column ID: 'abc' is not a valid number." { + t.Errorf("message: %q", msg) + } + invalid(model.RowChange{Op: model.OpDelete}) + invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(3, str("2024-01-01 10:00:00.5"))}}) + invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(4, str("2024-01-01 10:00:00"))}}) + invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(6, str("fast"))}}) + invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(1, str(strings.Repeat("x", maxBindBytes+1)))}}) + invalid(model.RowChange{Op: "upsert"}) + if msg := invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cell(5, str("DEADBEEF… (40000 bytes)"))}}); msg != "This value is only a preview and cannot be saved." { + t.Errorf("message: %q", msg) + } + target := sampleTarget() + target.Table = `bad"name` + if _, err := planChanges(model.ApplyRequest{Target: target, Changes: []model.RowChange{{Op: model.OpDelete, Key: []*string{str("1")}}}}); err == nil { + t.Fatal("bad table name accepted") + } +} + +func TestNotSaved(t *testing.T) { + if e := apperr.From(notSaved(2, 0)); e.Kind != apperr.Database || !strings.HasPrefix(e.Message, "Row 2 was not saved: 0 rows") { + t.Fatalf("got %#v", e) + } + if e := apperr.From(notSaved(1, 3)); e.Message != "Row 1 was not saved: 3 rows matched its key." { + t.Fatalf("got %q", e.Message) + } +} + +// --- Values --- + +func TestColumnTypeNamesAndKinds(t *testing.T) { + cases := []struct { + c column + name string + kind model.ValueKind + }{ + {column{dataType: goora.NCHAR, charLen: 30}, "VARCHAR2(30)", model.KindText}, + {column{dataType: goora.NCHAR, csForm: 2, charLen: 3}, "NVARCHAR2(3)", model.KindText}, + {column{dataType: goora.CHAR, charLen: 5}, "CHAR(5)", model.KindText}, + {column{dataType: goora.NUMBER, precision: 38, scale: 0xFF}, "NUMBER", model.KindNumber}, + {column{dataType: goora.NUMBER, precision: 0, scale: 0}, "NUMBER", model.KindNumber}, + {column{dataType: goora.NUMBER, precision: 10}, "NUMBER(10)", model.KindNumber}, + {column{dataType: goora.NUMBER, precision: 8, scale: 2}, "NUMBER(8,2)", model.KindNumber}, + {column{dataType: goora.NUMBER, precision: 5, scale: 0xFE}, "NUMBER(5,-2)", model.KindNumber}, + {column{dataType: goora.RAW, maxLen: 16}, "RAW(16)", model.KindBinary}, + {column{dataType: goora.DATE}, "DATE", model.KindTemporal}, + {column{dataType: goora.TIMESTAMP, scale: 6}, "TIMESTAMP(6)", model.KindTemporal}, + {column{dataType: goora.TIMESTAMPTZ, scale: 3}, "TIMESTAMP(3) WITH TIME ZONE", model.KindTemporal}, + {column{dataType: goora.TimeStampeLTZ, scale: 6}, "TIMESTAMP(6) WITH LOCAL TIME ZONE", model.KindTemporal}, + {column{dataType: goora.IntervalDS_DTY, precision: 2, scale: 6}, "INTERVAL DAY(2) TO SECOND(6)", model.KindTemporal}, + {column{dataType: goora.IntervalYM_DTY, precision: 2}, "INTERVAL YEAR(2) TO MONTH", model.KindTemporal}, + {column{dataType: goora.IBDouble}, "BINARY_DOUBLE", model.KindNumber}, + {column{dataType: goora.IBFloat}, "BINARY_FLOAT", model.KindNumber}, + {column{dataType: goora.OCIClobLocator}, "CLOB", model.KindText}, + {column{dataType: goora.OCIClobLocator, csForm: 2}, "NCLOB", model.KindText}, + {column{dataType: goora.OCIBlobLocator}, "BLOB", model.KindBinary}, + {column{dataType: goora.Boolean}, "BOOLEAN", model.KindBool}, + {column{dataType: goora.JSON}, "JSON", model.KindJSON}, + {column{dataType: goora.ROWID}, "ROWID", model.KindText}, + {column{dataType: goora.REFCURSOR}, "CURSOR", model.KindOther}, + {column{dataType: goora.XMLType, typeName: "XMLTYPE"}, "XMLTYPE", model.KindOther}, + } + for _, c := range cases { + if got := c.c.dataTypeName(); got != c.name { + t.Errorf("type %d: name %q, want %q", c.c.dataType, got, c.name) + } + if got := c.c.kind(); got != c.kind { + t.Errorf("type %d: kind %s, want %s", c.c.dataType, got, c.kind) + } + } +} + +func TestFormatValue(t *testing.T) { + ctx := context.Background() + date := time.Date(2024, 2, 29, 13, 45, 10, 250_000_000, time.UTC) + cases := []struct { + c column + v any + want string + }{ + {column{dataType: goora.NUMBER}, "12.", "12"}, + {column{dataType: goora.NUMBER}, "-0.5", "-0.5"}, + {column{dataType: goora.DATE}, date, "2024-02-29 13:45:10"}, + {column{dataType: goora.TIMESTAMP, scale: 6}, date, "2024-02-29 13:45:10.250000"}, + {column{dataType: goora.TIMESTAMP, scale: 0}, date, "2024-02-29 13:45:10"}, + {column{dataType: goora.TIMESTAMPTZ, scale: 3}, date.In(time.FixedZone("", -3*3600)), "2024-02-29 10:45:10.250 -03:00"}, + {column{dataType: goora.IntervalYM_DTY}, "+01-02", "P1Y2M"}, + {column{dataType: goora.IBDouble}, 0.1, "0.1"}, + {column{dataType: goora.IBFloat}, float32(1.5), "1.5"}, + {column{dataType: goora.IBFloat}, float32(0.1), "0.1"}, + {column{dataType: goora.IBDouble}, math.Inf(-1), "-Inf"}, + {column{dataType: goora.RAW}, []byte{0xDE, 0xAD}, "DEAD"}, + {column{dataType: goora.Boolean}, true, "TRUE"}, + {column{dataType: goora.VECTOR}, []uint8{1, 0xFF}, "[1,-1]"}, + {column{dataType: goora.VECTOR}, []float32{1.5, -2}, "[1.5,-2]"}, + {column{dataType: goora.NCHAR}, "olá", "olá"}, + {column{dataType: goora.OCIFileLocator}, goora.BFile{}, "(bfile)"}, + } + for _, c := range cases { + got := formatValue(ctx, c.c, c.v) + if got == nil || *got != c.want { + t.Errorf("%T %v: got %v, want %q", c.v, c.v, text(got), c.want) + } + } + if formatValue(ctx, column{dataType: goora.NUMBER}, nil) != nil { + t.Error("NULL is not nil") + } +} + +func TestBinaryValuesArePreviewed(t *testing.T) { + data := make([]byte, 40000) + preview := hexText(context.Background(), data) + if !strings.HasSuffix(preview, "… (40000 bytes)") || len(preview) != 2*binaryPreviewBytes+len("… (40000 bytes)") { + t.Fatalf("preview of %d characters", len(preview)) + } + full := hexText(drivers.WithFullValues(context.Background()), data) + if len(full) != 80000 { + t.Fatalf("full value of %d characters", len(full)) + } +} + +// --- Connection --- + +func TestVersionText(t *testing.T) { + v23 := 23<<24 | 5<<16 | 0<<12 | 24<<4 | 7 + v12 := 12<<24 | 2<<20 | 0<<12 | 1<<8 | 0 + for raw, want := range map[string]string{ + strconv.Itoa(v23): "23.5.0.24.7", + strconv.Itoa(v12): "12.2.0.1.0", + "odd": "odd", + } { + if got := versionText(raw); got != want { + t.Errorf("versionText(%s) = %q, want %q", raw, got, want) + } + } +} + +func TestEasyConnect(t *testing.T) { + for in, want := range map[string]string{ + "db.example:1522/sales": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db.example)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=sales)))", + "//db/sales": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)))", + "tcps://db:2484/sales?wallet=x": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=db)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=sales)))", + "db/sales:dedicated/inst1": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)(SERVER=DEDICATED)(INSTANCE_NAME=inst1)))", + "[::1]:1521/free": "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=::1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=free)))", + } { + got, err := easyConnect(in) + if err != nil || got != want { + t.Errorf("easyConnect(%q) = %q %v", in, got, err) + } + } + for _, bad := range []string{"db:1521", "ldap://db/x", "db:port/x", ":1521/x", "db extra/x"} { + if got, err := easyConnect(bad); err == nil || apperr.From(err).Kind != apperr.Invalid { + t.Errorf("easyConnect(%q) = %q %v", bad, got, err) + } + } +} + +func TestNetworkTarget(t *testing.T) { + p := model.DefaultProfile() + p.Engine = model.Oracle + p.Host = " db " + p.Port = 1522 + p.Database = "FREEPDB1" + p.OracleConnectType = model.OracleService + if got, _ := networkTarget(p); got != "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=FREEPDB1)))" { + t.Errorf("service: %s", got) + } + p.OracleConnectType = model.OracleSID + p.Port = 0 + if got, _ := networkTarget(p); got != "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db)(PORT=1521))(CONNECT_DATA=(SID=FREEPDB1)))" { + t.Errorf("sid: %s", got) + } + p.OracleConnectType = model.OracleCustom + p.ConnectString = " " + if _, err := networkTarget(p); apperr.From(err).Kind != apperr.Invalid { + t.Errorf("empty connect string: %v", err) + } + p.ConnectString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=h)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=s)))" + if got, _ := networkTarget(p); got != p.ConnectString { + t.Errorf("descriptor: %s", got) + } + p.ConnectString = "h:1/s" + if got, _ := networkTarget(p); !strings.Contains(got, "(HOST=h)(PORT=1)") { + t.Errorf("easy connect: %s", got) + } + // TNS aliases resolve through the folder of the profile. + dir := t.TempDir() + writeFile(t, dir, "tnsnames.ora", "SALES=(DESCRIPTION=(ADDRESS=(HOST=a)(PORT=1)))\n") + p.ConfigDir = &dir + p.ConnectString = "sales" + if got, err := networkTarget(p); err != nil || got != "(DESCRIPTION=(ADDRESS=(HOST=a)(PORT=1)))" { + t.Errorf("custom alias: %q %v", got, err) + } + p.OracleConnectType = model.OracleTNS + p.TnsAlias = "missing" + if _, err := networkTarget(p); err == nil || !strings.Contains(err.Error(), "tnsnames.ora") { + t.Errorf("missing alias: %v", err) + } +} + +func TestSplitOutput(t *testing.T) { + if got := splitOutput("3:olá0:5:mundo"); !reflect.DeepEqual(got, []string{"olá", "", "mundo"}) { + t.Fatalf("got %q", got) + } + if got := splitOutput("4:a:b:2:12"); !reflect.DeepEqual(got, []string{"a:b:", "12"}) { + t.Fatalf("got %q", got) + } + if got := splitOutput(""); len(got) != 0 { + t.Fatalf("got %q", got) + } +} + +func TestMapError(t *testing.T) { + if e := mapError(context.Canceled); e.Kind != apperr.Cancelled { + t.Fatalf("cancel: %#v", e) + } + if e := mapError(apperr.Invalidf("x")); e.Kind != apperr.Invalid { + t.Fatalf("app error: %#v", e) + } + oe := &network.OracleError{ErrCode: 942, ErrMsg: "ORA-00942: table or view does not exist\n"} + e := mapError(fmt.Errorf("query: %w", oe)) + if e.Kind != apperr.Database || e.Code != "ORA-00942" || e.Message != "table or view does not exist" || e.Position != nil { + t.Fatalf("ORA-00942: %#v", e) + } + if e := mapError(network.NewOracleError(1013)); e.Kind != apperr.Cancelled || e.Code != "ORA-01013" { + t.Fatalf("ORA-01013: %#v", e) + } + if e := mapError(io.EOF); e.Kind != apperr.Connection { + t.Fatalf("EOF: %#v", e) + } + if e := connectionError(&network.OracleError{ErrCode: 1017, ErrMsg: "ORA-01017: invalid credential"}); e.Kind != apperr.Connection || e.Code != "ORA-01017" { + t.Fatalf("ORA-01017: %#v", e) + } +} + +func TestRefusedConnectionFailsFast(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Skip(err) + } + port := l.Addr().(*net.TCPAddr).Port + _ = l.Close() + p := model.DefaultProfile() + p.Engine = model.Oracle + p.Host = "127.0.0.1" + p.Port = uint16(port) + p.User = "lowquery" + p.Database = "FREEPDB1" + p.OracleConnectType = model.OracleService + pw := "x" + started := time.Now() + _, err = Connect(context.Background(), p, &pw) + if e := apperr.From(err); e == nil || e.Kind != apperr.Connection { + t.Fatalf("got %v", err) + } + if elapsed := time.Since(started); elapsed > 10*time.Second { + t.Fatalf("took %v", elapsed) + } +} + +func TestBooleansFromTheTableTypes(t *testing.T) { + info := &tableInfo{owner: "APP", name: "T", columns: []tableColumn{tcol("ID", "NUMBER"), tcol("B", "BOOLEAN")}, key: []string{"ID"}} + cols := resultColumns(mustParse(t, "select b, b + 0 x from t"), info, []string{"B", "X"}) + if len(cols) != 2 || cols[0] == nil || cols[1] != nil { + t.Fatalf("columns: %+v", cols) + } + r := &model.ExecResult{ + Columns: []model.ColumnInfo{{Name: "B", TypeName: "NUMBER", Kind: model.KindNumber}, {Name: "X", TypeName: "NUMBER", Kind: model.KindNumber}}, + Rows: []model.Row{{str("1"), str("1")}, {str("0"), str("0")}, {nil, nil}}, + } + restoreBooleans(r, cols) + if r.Columns[0].Kind != model.KindBool || r.Columns[0].TypeName != "BOOLEAN" || r.Columns[1].Kind != model.KindNumber { + t.Fatalf("columns: %+v", r.Columns) + } + if got := texts(r.Rows); !reflect.DeepEqual(got, [][]string{{"TRUE", "1"}, {"FALSE", "0"}, {"NULL", "NULL"}}) { + t.Fatalf("rows: %v", got) + } + + target := model.EditTarget{Table: "T", Columns: []*model.EditColumn{ecol("ID", "NUMBER"), ecol("B", "BOOLEAN")}, Key: []int{0}} + p, err := planChanges(model.ApplyRequest{Target: target, Changes: []model.RowChange{ + {Op: model.OpUpdate, Key: []*string{str("1")}, Values: []model.CellValue{cell(1, str("FALSE"))}}, + }}) + if err != nil || p[0].sql != `update "T" set "B" = false where "ID" = to_number(:1)` { + t.Fatalf("plan: %+v %v", p, err) + } +} + +func TestDBMSOutputChunksFitStandardStrings(t *testing.T) { + if n := strings.Count(dbmsOutputSQL, ":= substr(buf,"); n != outputChunks { + t.Fatalf("%d chunks", n) + } + // Each chunk fits a 4000-byte bind, at up to 4 bytes per character. + if outputChunkChars*4 > 4000 { + t.Fatal("chunks too large") + } +} diff --git a/internal/drivers/oracle/sqltext.go b/internal/drivers/oracle/sqltext.go new file mode 100644 index 0000000..a109334 --- /dev/null +++ b/internal/drivers/oracle/sqltext.go @@ -0,0 +1,829 @@ +package oracle + +import ( + "fmt" + "sort" + "strconv" + "strings" + "unicode" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +// PrepareSQL prepares the text for Oracle: strips the trailing SQL*Plus slash +// and the trailing `;` of SQL statements. PL/SQL blocks keep the `;` (it is +// part of `END;`). +func PrepareSQL(sql string) string { + text := strings.TrimRightFunc(sql, unicode.IsSpace) + if stripped, ok := strings.CutSuffix(text, "/"); ok { + // Only strips the slash when it is alone on the last line. + if strings.HasSuffix(stripped, "\n") || strings.TrimRightFunc(stripped, unicode.IsSpace) == "" { + text = strings.TrimRightFunc(stripped, unicode.IsSpace) + } + } + if !IsPLSQL(text) { + for { + stripped, ok := strings.CutSuffix(text, ";") + if !ok { + break + } + text = strings.TrimRightFunc(stripped, unicode.IsSpace) + } + } + return text +} + +// IsPLSQL reports anonymous blocks and the creation of PL/SQL units. +func IsPLSQL(sql string) bool { + kw := drivers.FirstKeywords(sql, 6) + if len(kw) == 0 { + return false + } + switch kw[0] { + case "BEGIN", "DECLARE": + return true + case "CREATE": + default: + return false + } + i := 1 + if i < len(kw) && kw[i] == "OR" { + i += 2 // OR REPLACE + } + if i < len(kw) && (kw[i] == "EDITIONABLE" || kw[i] == "NONEDITIONABLE" || kw[i] == "EDITIONING") { + i++ + } + if i >= len(kw) { + return false + } + switch kw[i] { + case "PROCEDURE", "FUNCTION", "PACKAGE", "TRIGGER", "TYPE", "LIBRARY", "JAVA": + return true + } + return false +} + +// statementKind classifies a statement by its first keyword, as the Oracle +// drivers do. +type statementKind int + +const ( + kindOther statementKind = iota + kindQuery + kindDML + kindPLSQL + kindDDL +) + +func classify(sql string) statementKind { + text := strings.TrimLeftFunc(sql, func(r rune) bool { return unicode.IsSpace(r) || r == '(' }) + kw := drivers.FirstKeywords(text, 1) + if len(kw) == 0 { + return kindOther + } + switch kw[0] { + case "DECLARE", "BEGIN", "CALL": + return kindPLSQL + case "SELECT", "WITH": + return kindQuery + case "INSERT", "UPDATE", "DELETE", "MERGE": + return kindDML + case "CREATE", "ALTER", "DROP", "GRANT", "REVOKE", "ANALYZE", "AUDIT", "COMMENT", "TRUNCATE": + return kindDDL + } + return kindOther +} + +// --------------------------------------------------------------------------- +// Editable results +// +// The protocol does not say which table a result column comes from, so the +// statement text is checked conservatively: one SELECT over exactly one +// table, with a select list of `*`, `alias.*` and plain columns. The table is +// resolved and its key read from the data dictionary in one query, cached +// per table name as written until DDL, ALTER SESSION or PL/SQL runs. +// --------------------------------------------------------------------------- + +const ( + roTable = "Read-only: only rows from a table can be edited." + roJoin = "Read-only: the result combines columns from several tables." + roGrouped = "Read-only: grouped or distinct rows cannot be edited." + roSet = "Read-only: the result combines several queries." + roComplex = "Read-only: the query is too complex to map its rows to a table." + roUnknown = "Read-only: the table behind this result could not be identified." + roRemote = "Read-only: tables over database links cannot be edited." +) + +type tokKind int + +const ( + tokWord tokKind = iota // unquoted word, uppercased + tokQuoted // quoted identifier, as written + tokStr + tokNum + tokPunct +) + +type token struct { + kind tokKind + text string + ch rune +} + +func (t token) isPunct(c rune) bool { return t.kind == tokPunct && t.ch == c } +func (t token) isWord(w string) bool { return t.kind == tokWord && t.text == w } + +// lex returns the tokens of a statement, without comments. ok is false when a +// literal, quoted identifier or comment is not closed. +func lex(sql string) (out []token, ok bool) { + c := []rune(sql) + n := len(c) + at := func(i int) rune { + if i < n { + return c[i] + } + return 0 + } + isDigit := func(r rune) bool { return r >= '0' && r <= '9' } + i := 0 + for i < n { + ch, next := c[i], at(i+1) + switch { + case unicode.IsSpace(ch): + i++ + case ch == '-' && next == '-': + for i < n && c[i] != '\n' { + i++ + } + case ch == '/' && next == '*': + i += 2 + for i+1 < n && !(c[i] == '*' && c[i+1] == '/') { + i++ + } + if i+1 >= n { + return nil, false + } + i += 2 + case ch == '\'': + end, ok := skipString(c, i) + if !ok { + return nil, false + } + i = end + out = append(out, token{kind: tokStr}) + case (ch == 'q' || ch == 'Q') && next == '\'': + end, ok := skipQString(c, i+1) + if !ok { + return nil, false + } + i = end + out = append(out, token{kind: tokStr}) + case (ch == 'n' || ch == 'N') && next == '\'': + end, ok := skipString(c, i+1) + if !ok { + return nil, false + } + i = end + out = append(out, token{kind: tokStr}) + case (ch == 'n' || ch == 'N') && (next == 'q' || next == 'Q') && at(i+2) == '\'': + end, ok := skipQString(c, i+2) + if !ok { + return nil, false + } + i = end + out = append(out, token{kind: tokStr}) + case ch == '"': + start := i + 1 + end := start + for end < n && c[end] != '"' { + end++ + } + if end >= n || end == start { + return nil, false + } + out = append(out, token{kind: tokQuoted, text: string(c[start:end])}) + i = end + 1 + case isDigit(ch) || (ch == '.' && isDigit(next)): + for i < n && (isDigit(c[i]) || c[i] == '.') { + i++ + } + if i < n && (c[i] == 'e' || c[i] == 'E') { + sign := 0 + if at(i+1) == '+' || at(i+1) == '-' { + sign = 1 + } + if isDigit(at(i + 1 + sign)) { + i += 1 + sign + for i < n && isDigit(c[i]) { + i++ + } + } + } + if i < n && (c[i] == 'f' || c[i] == 'F' || c[i] == 'd' || c[i] == 'D') { + i++ + } + out = append(out, token{kind: tokNum}) + case unicode.IsLetter(ch): + start := i + for i < n && (unicode.IsLetter(c[i]) || unicode.IsDigit(c[i]) || unicode.IsNumber(c[i]) || + c[i] == '_' || c[i] == '$' || c[i] == '#') { + i++ + } + out = append(out, token{kind: tokWord, text: strings.ToUpper(string(c[start:i]))}) + default: + out = append(out, token{kind: tokPunct, ch: ch}) + i++ + } + } + return out, true +} + +// skipString returns the end of a '...' literal that starts at quote. +func skipString(c []rune, quote int) (int, bool) { + i := quote + 1 + for i < len(c) { + if c[i] == '\'' { + if i+1 < len(c) && c[i+1] == '\'' { + i += 2 + continue + } + return i + 1, true + } + i++ + } + return 0, false +} + +// skipQString returns the end of a q'[...]' literal whose quote is at quote. +func skipQString(c []rune, quote int) (int, bool) { + if quote+1 >= len(c) { + return 0, false + } + closing := c[quote+1] + switch closing { + case '[': + closing = ']' + case '(': + closing = ')' + case '{': + closing = '}' + case '<': + closing = '>' + } + for i := quote + 2; i+1 < len(c); i++ { + if c[i] == closing && c[i+1] == '\'' { + return i + 2, true + } + } + return 0, false +} + +type selItemKind int + +const ( + selStar selItemKind = iota // `*` (no qualifier) or `q.*` + selColumn // a plain column + selExpr // anything else +) + +type selItem struct { + kind selItemKind + qual []string + name string + alias *string +} + +type selectShape struct { + schema *string + table string + alias *string + items []selItem +} + +func (s *selectShape) qualifierMatches(qual []string) bool { + switch len(qual) { + case 0: + return true + case 1: + if s.alias != nil { + return qual[0] == *s.alias + } + return qual[0] == s.table + case 2: + return s.alias == nil && s.schema != nil && qual[0] == *s.schema && qual[1] == s.table + } + return false +} + +func nameTok(toks []token, i int) (string, bool) { + if i < len(toks) && (toks[i].kind == tokWord || toks[i].kind == tokQuoted) { + return toks[i].text, true + } + return "", false +} + +func wordAt(toks []token, i int) string { + if i < len(toks) && toks[i].kind == tokWord { + return toks[i].text + } + return "" +} + +// notAlias holds the words that end the table reference instead of naming +// its alias. +var notAlias = map[string]bool{ + "WHERE": true, "ORDER": true, "FETCH": true, "OFFSET": true, "FOR": true, "GROUP": true, + "HAVING": true, "CONNECT": true, "START": true, "UNION": true, "INTERSECT": true, + "MINUS": true, "EXCEPT": true, "JOIN": true, "INNER": true, "LEFT": true, "RIGHT": true, + "FULL": true, "CROSS": true, "NATURAL": true, "OUTER": true, "PIVOT": true, "UNPIVOT": true, + "MODEL": true, "SAMPLE": true, "PARTITION": true, "SUBPARTITION": true, "AS": true, + "VERSIONS": true, "MATCH_RECOGNIZE": true, "WINDOW": true, "LIMIT": true, "QUALIFY": true, + "APPLY": true, "LATERAL": true, "WITH": true, +} + +// parseSelect checks that the statement reads rows of one table and nothing +// else. On failure it returns the read-only reason. +func parseSelect(sql string) (*selectShape, string) { + toks, ok := lex(sql) + if !ok { + return nil, roComplex + } + if wordAt(toks, 0) != "SELECT" { + return nil, roTable + } + i := 1 + switch wordAt(toks, i) { + case "DISTINCT", "UNIQUE": + return nil, roGrouped + case "ALL": + i++ + } + + // Select list, up to FROM. + var items []selItem + depth := 0 + start := i + for { + if i >= len(toks) { + return nil, roTable + } + t := toks[i] + switch { + case t.isPunct('('): + depth++ + case t.isPunct(')'): + if depth == 0 { + return nil, roComplex + } + depth-- + case t.isPunct(',') && depth == 0: + items = append(items, parseItem(toks[start:i])) + start = i + 1 + case t.isWord("FROM") && depth == 0: + items = append(items, parseItem(toks[start:i])) + } + if t.isWord("FROM") && depth == 0 { + break + } + i++ + } + + // FROM [schema.]table [alias] + i++ + if i < len(toks) && toks[i].isPunct('(') { + return nil, roTable + } + first, ok := nameTok(toks, i) + if !ok { + return nil, roComplex + } + parts := []string{first} + i++ + for i < len(toks) && toks[i].isPunct('.') { + part, ok := nameTok(toks, i+1) + if !ok { + return nil, roComplex + } + parts = append(parts, part) + i += 2 + } + if len(parts) > 2 { + return nil, roComplex + } + if i < len(toks) { + // Table functions, `only (...)`, `lateral (...)`. + if toks[i].isPunct('(') { + return nil, roTable + } + if toks[i].isPunct('@') { + return nil, roRemote + } + } + var alias *string + if i < len(toks) { + t := toks[i] + if t.kind == tokQuoted || (t.kind == tokWord && !notAlias[t.text]) { + a := t.text + alias = &a + i++ + } + } + if i < len(toks) { + t := toks[i] + switch { + case t.kind == tokWord: + switch t.text { + case "WHERE", "ORDER", "FETCH", "OFFSET", "FOR": + case "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "NATURAL", "OUTER", "APPLY": + return nil, roJoin + case "GROUP", "HAVING": + return nil, roGrouped + case "UNION", "INTERSECT", "MINUS", "EXCEPT": + return nil, roSet + default: + return nil, roComplex + } + case t.isPunct(','): + return nil, roJoin + default: + return nil, roComplex + } + } + + // The remaining clauses must not group, combine or walk the rows. + rest := toks[i:] + depth = 0 + for j, t := range rest { + switch { + case t.isPunct('('): + depth++ + case t.isPunct(')'): + if depth > 0 { + depth-- + } + case t.kind == tokWord && depth == 0: + next := wordAt(rest, j+1) + switch { + case t.text == "GROUP" && next == "BY", t.text == "HAVING": + return nil, roGrouped + case t.text == "UNION", t.text == "INTERSECT", t.text == "MINUS", t.text == "EXCEPT": + return nil, roSet + case t.text == "CONNECT" && next == "BY", t.text == "START" && next == "WITH", + t.text == "DIMENSION" && next == "BY", t.text == "ORDER" && next == "SIBLINGS": + return nil, roComplex + } + } + } + + shape := &selectShape{table: parts[len(parts)-1], alias: alias, items: items} + if len(parts) == 2 { + shape.schema = &parts[0] + } + return shape, "" +} + +// parseItem reads one select-list item: `*`, `q.*`, a plain column with an +// optional alias, or anything else. +func parseItem(t []token) selItem { + if len(t) == 1 && t[0].isPunct('*') { + return selItem{kind: selStar} + } + var parts []string + i := 0 + for { + if i < len(t) && (t[i].kind == tokWord || t[i].kind == tokQuoted) { + parts = append(parts, t[i].text) + } else if i < len(t) && t[i].isPunct('*') && len(parts) > 0 && i+1 == len(t) { + return selItem{kind: selStar, qual: parts} + } else { + return selItem{kind: selExpr} + } + i++ + if i < len(t) && t[i].isPunct('.') { + i++ + } else { + break + } + } + if len(parts) > 3 { + return selItem{kind: selExpr} + } + var alias *string + rest := t[i:] + switch { + case len(rest) == 0: + case len(rest) == 2 && rest[0].isWord("AS"): + a, ok := nameTok(rest, 1) + if !ok { + return selItem{kind: selExpr} + } + alias = &a + case len(rest) == 1: + a, ok := nameTok(rest, 0) + if !ok { + return selItem{kind: selExpr} + } + alias = &a + default: + return selItem{kind: selExpr} + } + return selItem{kind: selColumn, qual: parts[:len(parts)-1], name: parts[len(parts)-1], alias: alias} +} + +// tableInfo describes a table found in the data dictionary. +type tableInfo struct { + owner string + name string + // Visible columns in `select *` order. + columns []tableColumn + key []string + primary bool +} + +type tableColumn struct { + name string + typeName string + nullable bool + generated bool +} + +// lookup is a cached dictionary lookup: a table, or the reason its rows are +// read-only. +type lookup struct { + table *tableInfo + readOnly string +} + +// resultColumns maps result columns (by their names in the result) to table +// columns: nil for expressions, and a nil slice when the result does not +// line up with the statement text. +func resultColumns(shape *selectShape, info *tableInfo, resultNames []string) []*tableColumn { + var mapped []*tableColumn + var expected []string + for _, item := range shape.items { + switch item.kind { + case selStar: + if !shape.qualifierMatches(item.qual) { + return nil + } + for i := range info.columns { + mapped = append(mapped, &info.columns[i]) + expected = append(expected, info.columns[i].name) + } + case selColumn: + var found *tableColumn + name := "" + if shape.qualifierMatches(item.qual) { + for i := range info.columns { + if info.columns[i].name == item.name { + found, name = &info.columns[i], info.columns[i].name + if item.alias != nil { + name = *item.alias + } + break + } + } + } + mapped = append(mapped, found) + expected = append(expected, name) + default: + mapped = append(mapped, nil) + expected = append(expected, "") + } + } + if len(mapped) != len(resultNames) { + return nil + } + for i, m := range mapped { + if m != nil && resultNames[i] != expected[i] { + return nil + } + } + return mapped +} + +// mapColumns maps result columns (by their names in the result) to table +// columns and finds the key in the result. +func mapColumns(shape *selectShape, info *tableInfo, resultNames []string) (*model.EditTarget, string) { + mapped := resultColumns(shape, info, resultNames) + if mapped == nil { + return nil, "Read-only: the result columns could not be matched to table " + info.name + "." + } + columns := make([]*model.EditColumn, len(mapped)) + for i, m := range mapped { + if m != nil && !m.generated && colTypeOf(m.typeName) != colNone { + columns[i] = &model.EditColumn{Name: m.name, TypeName: m.typeName} + } + } + + key := make([]int, 0, len(info.key)) + for _, k := range info.key { + found := -1 + for i, c := range columns { + if c != nil && c.Name == k { + found = i + break + } + } + if found >= 0 { + key = append(key, found) + continue + } + for _, m := range mapped { + if m != nil && m.name == k { + return nil, "Read-only: key column " + k + " has a type that cannot be edited here." + } + } + kind := "key" + if info.primary { + kind = "primary key" + } + return nil, fmt.Sprintf("Read-only: add the %s columns (%s) to the query to edit rows.", kind, strings.Join(info.key, ", ")) + } + owner := info.owner + return &model.EditTarget{Schema: &owner, Table: info.name, Columns: columns, Key: key}, "" +} + +// lookupSQL resolves a table name the way Oracle does (current schema, then +// public synonyms; one level of synonym) and reads its columns and keys, in +// one round trip. +const lookupSQL = ` +with named as ( + select o.owner, o.object_name, o.object_type + from all_objects o + where o.owner = nvl(:1, sys_context('USERENV', 'CURRENT_SCHEMA')) + and o.object_name = :2 + and o.subobject_name is null + and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW') + union all + select s.owner, s.synonym_name, 'SYNONYM' + from all_synonyms s + where :3 is null and s.owner = 'PUBLIC' and s.synonym_name = :4 + and not exists ( + select 1 from all_objects o + where o.owner = sys_context('USERENV', 'CURRENT_SCHEMA') + and o.object_name = :5 + and o.subobject_name is null + and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW')) +), +resolved as ( + select n.object_type kind, n.owner, n.object_name name + from named n + where n.object_type <> 'SYNONYM' + union all + select case when s.db_link is not null then 'REMOTE' + else nvl(o.object_type, 'MISSING') end, + s.table_owner, s.table_name + from named n + join all_synonyms s on s.owner = n.owner and s.synonym_name = n.object_name + left join all_objects o on o.owner = s.table_owner and o.object_name = s.table_name + and o.subobject_name is null + and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW') + where n.object_type = 'SYNONYM' +) +select 'O', r.kind, r.owner, r.name, cast(null as varchar2(3)), cast(null as varchar2(40)) + from resolved r +union all +select 'C', c.column_name, + case + when c.data_type in ('VARCHAR2', 'NVARCHAR2', 'CHAR', 'NCHAR', 'RAW') + then c.data_type || '(' || + case when c.char_length > 0 then c.char_length else c.data_length end || ')' + when c.data_type = 'NUMBER' and c.data_precision is not null + then 'NUMBER(' || c.data_precision || + case when c.data_scale <> 0 then ',' || c.data_scale end || ')' + when c.data_type = 'FLOAT' and c.data_precision is not null + then 'FLOAT(' || c.data_precision || ')' + else c.data_type end, + c.nullable, c.virtual_column, to_char(c.column_id) + from resolved r + join all_tab_cols c on c.owner = r.owner and c.table_name = r.name + where r.kind = 'TABLE' and c.hidden_column = 'NO' and c.column_id is not null +union all +select 'K', k.constraint_type, k.constraint_name, kc.column_name, + cast(null as varchar2(3)), to_char(kc.position) + from resolved r + join all_constraints k on k.owner = r.owner and k.table_name = r.name + join all_cons_columns kc on kc.owner = k.owner + and kc.constraint_name = k.constraint_name and kc.table_name = k.table_name + where r.kind = 'TABLE' and k.constraint_type in ('P', 'U') and k.status = 'ENABLED'` + +func atoiOrMax(s string) int { + n, err := strconv.Atoi(s) + if err != nil { + return int(^uint(0) >> 1) + } + return n +} + +// buildTableInfo builds the table description from the rows of lookupSQL. +func buildTableInfo(written string, rows [][]string) lookup { + var kinds []string + var owner, name string + found := false + type positioned struct { + pos int + col tableColumn + } + var cols []positioned + type constraintKey struct{ kind, name string } + type keyCol struct { + pos int + name string + } + constraints := map[constraintKey][]keyCol{} + for _, r := range rows { + if len(r) < 6 { + continue + } + switch r[0] { + case "O": + if r[1] == "TABLE" { + owner, name, found = r[2], r[3], true + } + kinds = append(kinds, r[1]) + case "C": + cols = append(cols, positioned{pos: atoiOrMax(r[5]), col: tableColumn{ + name: r[1], typeName: r[2], nullable: r[3] != "N", generated: r[4] == "YES", + }}) + case "K": + k := constraintKey{r[1], r[2]} + constraints[k] = append(constraints[k], keyCol{pos: atoiOrMax(r[5]), name: r[3]}) + } + } + has := func(k string) bool { + for _, x := range kinds { + if x == k { + return true + } + } + return false + } + switch { + case has("MATERIALIZED VIEW"): + return lookup{readOnly: "Read-only: " + written + " is a materialized view."} + case has("REMOTE"): + return lookup{readOnly: roRemote} + case has("VIEW"): + return lookup{readOnly: "Read-only: " + written + " is a view; only tables can be edited."} + case !found: + return lookup{readOnly: roTable} + } + sort.SliceStable(cols, func(i, j int) bool { return cols[i].pos < cols[j].pos }) + columns := make([]tableColumn, len(cols)) + for i, c := range cols { + columns[i] = c.col + } + + // The primary key, else the narrowest unique key on NOT NULL columns. + type candidate struct { + primary bool + name string + cols []string + } + var keys []candidate + for k, kc := range constraints { + sort.SliceStable(kc, func(i, j int) bool { return kc[i].pos < kc[j].pos }) + names := make([]string, len(kc)) + for i, c := range kc { + names[i] = c.name + } + primary := k.kind == "P" + if !primary { + allNotNull := true + for _, n := range names { + ok := false + for _, c := range columns { + if c.name == n && !c.nullable { + ok = true + break + } + } + if !ok { + allNotNull = false + break + } + } + if !allNotNull { + continue + } + } + keys = append(keys, candidate{primary: primary, name: k.name, cols: names}) + } + // Ordered by constraint name first, as the dictionary rows were grouped. + sort.Slice(keys, func(i, j int) bool { + a, b := keys[i], keys[j] + if a.primary != b.primary { + return a.primary + } + if len(a.cols) != len(b.cols) { + return len(a.cols) < len(b.cols) + } + return a.name < b.name + }) + if len(keys) == 0 { + return lookup{readOnly: "Read-only: table " + name + " has no primary key."} + } + return lookup{table: &tableInfo{owner: owner, name: name, columns: columns, key: keys[0].cols, primary: keys[0].primary}} +} diff --git a/internal/drivers/oracle/tns.go b/internal/drivers/oracle/tns.go new file mode 100644 index 0000000..0398df7 --- /dev/null +++ b/internal/drivers/oracle/tns.go @@ -0,0 +1,502 @@ +package oracle + +// Oracle network configuration: finds tnsnames.ora the way Oracle clients do +// and reads it without requiring UTF-8. +// +// Search order: TNS_ADMIN, ORACLE_HOME/network/admin, the Oracle homes +// registered in the Windows registry, Oracle clients and Instant Clients on +// the library path, then the system folders used on Linux and macOS. +// +// Corporate tnsnames.ora files are often saved as Latin-1 (accented +// comments). Aliases are resolved here and the driver receives the full +// descriptor. + +import ( + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +const ( + tnsNames = "tnsnames.ora" + maxIfileDepth = 8 +) + +// TNSEntry is one alias of a tnsnames.ora. +type TNSEntry struct { + Alias string `json:"alias"` + Descriptor string `json:"descriptor"` + Host *string `json:"host"` + Port *uint16 `json:"port"` + ServiceName *string `json:"serviceName"` + SID *string `json:"sid"` + Protocol *string `json:"protocol"` +} + +// TNSSource is a folder with a tnsnames.ora, as shown in the "Oracle +// client" picker. +type TNSSource struct { + Dir string `json:"dir"` + // Oracle home name (OraClient19Home1) or the folder itself. + Label string `json:"label"` + // Where it was found: TNS_ADMIN, ORACLE_HOME, Windows registry... + Origin string `json:"origin"` + Entries []TNSEntry `json:"entries"` + Error *string `json:"error"` +} + +type tnsCandidate struct { + dir, label, origin string +} + +// TNSSources returns every folder with a tnsnames.ora found on this machine, +// in search order (the oracle_tns_sources command). +func TNSSources() []TNSSource { + seen := map[string]bool{} + out := []TNSSource{} + for _, c := range tnsCandidates(envValue) { + if !isFile(filepath.Join(c.dir, tnsNames)) { + continue + } + key := pathKey(c.dir) + if seen[key] { + continue + } + seen[key] = true + out = append(out, readSource(c.dir, c.label, c.origin)) + } + return out +} + +// TNSFolder reads a folder picked by the user (the oracle_tns_folder +// command). Accepts the network/admin folder, an Oracle home or Instant +// Client folder, or the tnsnames.ora file. +func TNSFolder(path string) (*TNSSource, error) { + dir, ok := normalizeDir(strings.TrimSpace(path)) + if !ok { + return nil, apperr.NotFoundf("No %s found in %s.", tnsNames, path) + } + src := readSource(dir, dir, "Selected folder") + return &src, nil +} + +// ResolveTNS resolves an alias to its descriptor and the folder it came +// from. With configDir, only that folder is used; otherwise the discovered +// folders are searched in order. +func ResolveTNS(alias string, configDir string) (descriptor, dir string, err error) { + alias = strings.TrimSpace(alias) + if alias == "" { + return "", "", apperr.Invalidf("Choose a TNS alias.") + } + var sources []TNSSource + if strings.TrimSpace(configDir) != "" { + src, err := TNSFolder(configDir) + if err != nil { + return "", "", err + } + sources = []TNSSource{*src} + } else { + sources = TNSSources() + } + if len(sources) == 0 { + return "", "", apperr.Connectionf( + "No %s found. Set TNS_ADMIN, install an Oracle client or choose the folder in the connection.", tnsNames) + } + for _, src := range sources { + if e := findEntry(src.Entries, alias, defaultDomain(src.Dir)); e != nil { + return e.Descriptor, src.Dir, nil + } + } + searched := make([]string, len(sources)) + for i, src := range sources { + searched[i] = filepath.Join(src.Dir, tnsNames) + } + return "", "", apperr.Connectionf("TNS alias \"%s\" was not found in %s.", alias, strings.Join(searched, ", ")) +} + +// defaultTNSDir is the first discovered folder, used for aliases typed in a +// custom connect string when the profile has no folder of its own. +func defaultTNSDir() string { + if sources := TNSSources(); len(sources) > 0 { + return sources[0].Dir + } + return "" +} + +// findEntry matches aliases without case; NAMES.DEFAULT_DOMAIN from +// sqlnet.ora is appended when the bare name is not defined, as Oracle +// clients do. +func findEntry(entries []TNSEntry, alias, domain string) *TNSEntry { + for i := range entries { + if strings.EqualFold(entries[i].Alias, alias) { + return &entries[i] + } + } + if domain == "" || strings.Contains(alias, ".") { + return nil + } + qualified := alias + "." + domain + for i := range entries { + if strings.EqualFold(entries[i].Alias, qualified) { + return &entries[i] + } + } + return nil +} + +func defaultDomain(dir string) string { + data, err := os.ReadFile(filepath.Join(dir, "sqlnet.ora")) + if err != nil { + return "" + } + for _, p := range parseTNS(decodeText(data)) { + for _, k := range p.keys { + if strings.EqualFold(k, "names.default_domain") { + return strings.TrimSpace(p.value) + } + } + } + return "" +} + +func readSource(dir, label, origin string) TNSSource { + var entries []TNSEntry + src := TNSSource{Dir: dir, Label: label, Origin: origin, Entries: []TNSEntry{}} + if err := readTNSFile(filepath.Join(dir, tnsNames), dir, &entries, map[string]bool{}, 0); err != nil { + msg := err.Error() + src.Error = &msg + } + // A later definition replaces an earlier one, keeping its position. + index := map[string]int{} + for _, e := range entries { + key := strings.ToLower(e.Alias) + if i, ok := index[key]; ok { + src.Entries[i] = e + continue + } + index[key] = len(src.Entries) + src.Entries = append(src.Entries, e) + } + return src +} + +type tnsError string + +func (e tnsError) Error() string { return string(e) } + +func readTNSFile(file, dir string, out *[]TNSEntry, visited map[string]bool, depth int) error { + key := pathKey(file) + if depth > maxIfileDepth || visited[key] { + return tnsError("IFILE cycle or nesting too deep at " + file) + } + visited[key] = true + data, err := os.ReadFile(file) + if err != nil { + return err + } + for _, p := range parseTNS(decodeText(data)) { + if len(p.keys) == 1 && strings.EqualFold(p.keys[0], "ifile") { + included := strings.Trim(strings.TrimSpace(p.value), `"`) + if !filepath.IsAbs(included) { + included = filepath.Join(dir, included) + } + if err := readTNSFile(included, dir, out, visited, depth+1); err != nil { + return err + } + continue + } + for _, alias := range p.keys { + *out = append(*out, tnsEntry(alias, p.value)) + } + } + return nil +} + +func tnsEntry(alias, value string) TNSEntry { + descriptor := strings.Join(strings.Fields(value), " ") + e := TNSEntry{ + Alias: alias, + Descriptor: descriptor, + Host: descriptorParam(descriptor, "HOST"), + ServiceName: descriptorParam(descriptor, "SERVICE_NAME"), + SID: descriptorParam(descriptor, "SID"), + } + if p := descriptorParam(descriptor, "PORT"); p != nil { + if n, err := strconv.ParseUint(*p, 10, 16); err == nil { + port := uint16(n) + e.Port = &port + } + } + if p := descriptorParam(descriptor, "PROTOCOL"); p != nil { + upper := strings.ToUpper(*p) + e.Protocol = &upper + } + return e +} + +// decodeText reads UTF-8 when valid, otherwise Latin-1 (every byte is a code +// point). +func decodeText(data []byte) string { + data = []byte(strings.TrimPrefix(string(data), "\xEF\xBB\xBF")) + if utf8.Valid(data) { + return string(data) + } + runes := make([]rune, len(data)) + for i, b := range data { + runes[i] = rune(b) + } + return string(runes) +} + +// descriptorParam returns the first (KEY = value) in a descriptor, without +// case. +func descriptorParam(descriptor, key string) *string { + i := 0 + for { + off := strings.IndexByte(descriptor[i:], '(') + if off < 0 { + return nil + } + j := i + off + 1 + for j < len(descriptor) && isASCIISpace(descriptor[j]) { + j++ + } + end := j + len(key) + if end <= len(descriptor) && strings.EqualFold(descriptor[j:end], key) { + k := end + for k < len(descriptor) && isASCIISpace(descriptor[k]) { + k++ + } + if k < len(descriptor) && descriptor[k] == '=' { + rest := descriptor[k+1:] + if p := strings.IndexByte(rest, ')'); p >= 0 { + rest = rest[:p] + } + value := strings.TrimSpace(rest) + if value != "" && !strings.HasPrefix(value, "(") { + return &value + } + } + } + i = i + off + 1 + } +} + +func isASCIISpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' +} + +type tnsPair struct { + keys []string + value string +} + +// parseTNS reads `name[, name...] = value` entries. A value starting with +// `(` runs until its parentheses balance; any other value ends at the line +// break. `#` starts a comment. +func parseTNS(text string) []tnsPair { + chars := []rune(text) + n := len(chars) + i := 0 + var out []tnsPair + skipComment := func() { + for i < n && chars[i] != '\n' { + i++ + } + } + for { + // Whitespace and comments before the names. + for i < n && (unicode.IsSpace(chars[i]) || chars[i] == '#') { + if chars[i] == '#' { + skipComment() + } else { + i++ + } + } + if i >= n { + break + } + + // Names up to '='. + var names strings.Builder + malformed := false + for i < n && chars[i] != '=' { + switch chars[i] { + case '#': + skipComment() + case '(', ')': + malformed = true + i++ + default: + names.WriteRune(chars[i]) + i++ + } + } + if i >= n { + break + } + i++ // '=' + + // Value. + for i < n && unicode.IsSpace(chars[i]) { + i++ + } + var value strings.Builder + if i < n && chars[i] == '(' { + depth := 0 + for i < n { + c := chars[i] + if c == '#' { + skipComment() + continue + } + value.WriteRune(c) + i++ + if c == '(' { + depth++ + } else if c == ')' { + if depth > 0 { + depth-- + } + if depth == 0 { + break + } + } + } + } else { + for i < n && chars[i] != '\n' && chars[i] != '#' { + value.WriteRune(chars[i]) + i++ + } + } + + if malformed { + continue + } + // Each name is the last word before a comma; stray text before it (an + // unterminated line) is ignored. + var keys []string + for _, part := range strings.Split(names.String(), ",") { + if words := strings.Fields(part); len(words) > 0 { + keys = append(keys, words[len(words)-1]) + } + } + v := strings.TrimSpace(value.String()) + if len(keys) > 0 && v != "" { + out = append(out, tnsPair{keys: keys, value: v}) + } + } + return out +} + +func isFile(path string) bool { + info, err := os.Stat(path) + return err == nil && info.Mode().IsRegular() +} + +func pathKey(path string) string { + p := path + if abs, err := filepath.Abs(path); err == nil { + p = abs + } + if real, err := filepath.EvalSymlinks(p); err == nil { + p = real + } + if runtime.GOOS == "windows" { + return strings.ToLower(p) + } + return p +} + +// normalizeDir returns the folder holding tnsnames.ora: the folder itself, +// its network/admin (Oracle home or Instant Client folder) or the parent of +// the file. +func normalizeDir(path string) (string, bool) { + if path == "" { + return "", false + } + if isFile(path) { + return filepath.Dir(path), true + } + for _, d := range []string{path, filepath.Join(path, "network", "admin")} { + if isFile(filepath.Join(d, tnsNames)) { + return d, true + } + } + return "", false +} + +func clientLibraryIn(dir string) bool { + entries, err := os.ReadDir(dir) + if err != nil { + return false + } + for _, e := range entries { + name := strings.ToLower(e.Name()) + if name == "oci.dll" || strings.HasPrefix(name, "libclntsh.so") || + (strings.HasPrefix(name, "libclntsh.") && strings.HasSuffix(name, ".dylib")) { + return true + } + } + return false +} + +// envValue is an environment variable, empty when unset or blank. +func envValue(name string) string { + v := os.Getenv(name) + if strings.TrimSpace(v) == "" { + return "" + } + return v +} + +func tnsCandidates(env func(string) string) []tnsCandidate { + var out []tnsCandidate + push := func(dir, label, origin string) { + out = append(out, tnsCandidate{dir: dir, label: label, origin: origin}) + } + if dir := strings.TrimSpace(env("TNS_ADMIN")); dir != "" { + push(dir, dir, "TNS_ADMIN") + } + if home := strings.TrimSpace(env("ORACLE_HOME")); home != "" { + push(filepath.Join(home, "network", "admin"), home, "ORACLE_HOME") + } + for _, h := range registryHomes() { + push(h.dir, h.label, h.origin) + } + + libVars := []string{"PATH"} + if runtime.GOOS != "windows" { + libVars = append(libVars, "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH") + } + for _, name := range libVars { + value := env(name) + if value == "" { + continue + } + for _, dir := range filepath.SplitList(value) { + if dir == "" || !clientLibraryIn(dir) { + continue + } + // Instant Client keeps network/admin next to the library; a full + // client has it next to its bin folder. + push(filepath.Join(dir, "network", "admin"), dir, "Instant Client on PATH") + if home := filepath.Dir(filepath.Clean(dir)); home != filepath.Clean(dir) { + push(filepath.Join(home, "network", "admin"), home, "Oracle client on PATH") + } + } + } + + if runtime.GOOS != "windows" { + for _, dir := range []string{"/etc", "/var/opt/oracle"} { + push(dir, dir, "System folder") + } + } + return out +} diff --git a/internal/drivers/oracle/tns_other.go b/internal/drivers/oracle/tns_other.go new file mode 100644 index 0000000..f5f8ba9 --- /dev/null +++ b/internal/drivers/oracle/tns_other.go @@ -0,0 +1,11 @@ +//go:build !windows + +package oracle + +type registryHome struct { + dir, label, origin string +} + +// registryHomes is empty outside Windows: Oracle homes are only registered +// in the Windows registry. +func registryHomes() []registryHome { return nil } diff --git a/internal/drivers/oracle/tns_test.go b/internal/drivers/oracle/tns_test.go new file mode 100644 index 0000000..1e7a738 --- /dev/null +++ b/internal/drivers/oracle/tns_test.go @@ -0,0 +1,229 @@ +package oracle + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +const sampleTNS = ` +# Produção — comentário com acento +ERP, ERP.WORLD = + (DESCRIPTION = + (ADDRESS = (PROTOCOL = TCP)(HOST = erp-db.example)(PORT = 1521)) # inline comment + (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = erppdb)) + ) + +legacy=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=old)(PORT=2484))(CONNECT_DATA=(SID=ORCL))) +EZ = db.example:1521/sales +` + +func writeFile(t *testing.T, dir, name, content string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } +} + +func TestParseTNSAliasesDescriptorsAndFields(t *testing.T) { + var entries []TNSEntry + for _, p := range parseTNS(sampleTNS) { + for _, k := range p.keys { + entries = append(entries, tnsEntry(k, p.value)) + } + } + var names []string + for _, e := range entries { + names = append(names, e.Alias) + } + if strings.Join(names, ",") != "ERP,ERP.WORLD,legacy,EZ" { + t.Fatalf("aliases: %v", names) + } + erp := entries[0] + if text(erp.Host) != "erp-db.example" || erp.Port == nil || *erp.Port != 1521 || text(erp.ServiceName) != "erppdb" || + text(erp.Protocol) != "TCP" || erp.SID != nil { + t.Fatalf("ERP: %+v", erp) + } + if strings.Contains(erp.Descriptor, "inline comment") || !strings.HasPrefix(erp.Descriptor, "(DESCRIPTION = (ADDRESS") { + t.Fatalf("descriptor: %q", erp.Descriptor) + } + if text(entries[2].SID) != "ORCL" || text(entries[2].Protocol) != "TCPS" || *entries[2].Port != 2484 { + t.Fatalf("legacy: %+v", entries[2]) + } + if entries[3].Descriptor != "db.example:1521/sales" || entries[3].Host != nil { + t.Fatalf("EZ: %+v", entries[3]) + } +} + +func TestDecodeLatin1Files(t *testing.T) { + text := decodeText([]byte("# Produ\xe7\xe3o\nA=(DESCRIPTION=(ADDRESS=(HOST=h)(PORT=1)))\n")) + if !strings.Contains(text, "Produção") || len(parseTNS(text)) != 1 { + t.Fatalf("decoded %q", text) + } + if got := decodeText([]byte("\xEF\xBB\xBFA=(x)")); got != "A=(x)" { + t.Fatalf("BOM: %q", got) + } +} + +func TestTNSFoldersWithIFileAndDefaultDomain(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "tnsnames.ora", + "IFILE = extra.ora\nSALES.WORLD=(DESCRIPTION=(ADDRESS=(HOST=a)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=s)))\n") + writeFile(t, dir, "extra.ora", "HR = (DESCRIPTION=(ADDRESS=(HOST=b)(PORT=1522)))\nsales.world=(DESCRIPTION=(ADDRESS=(HOST=old)))\n") + writeFile(t, dir, "sqlnet.ora", "NAMES.DEFAULT_DOMAIN = WORLD\n") + + src, err := TNSFolder(dir) + if err != nil { + t.Fatal(err) + } + var names []string + for _, e := range src.Entries { + names = append(names, e.Alias) + } + // The later SALES.WORLD replaces the one from the IFILE, keeping its place. + if strings.Join(names, ",") != "HR,SALES.WORLD" || src.Error != nil || src.Origin != "Selected folder" { + t.Fatalf("source: %v %v", names, src.Error) + } + + descriptor, found, err := ResolveTNS("sales", dir) + if err != nil || !strings.Contains(descriptor, "SERVICE_NAME=s") || pathKey(found) != pathKey(dir) { + t.Fatalf("sales: %q %q %v", descriptor, found, err) + } + if hr, _, err := ResolveTNS("hr", dir); err != nil || !strings.Contains(hr, "HOST=b") { + t.Fatalf("hr: %q %v", hr, err) + } + if _, _, err := ResolveTNS("missing", dir); err == nil || !strings.Contains(err.Error(), "tnsnames.ora") { + t.Fatalf("missing: %v", err) + } + if _, _, err := ResolveTNS(" ", dir); err == nil { + t.Fatal("empty alias accepted") + } + + // The Oracle home / Instant Client folder works too, and the file itself. + home := filepath.Join(dir, "home") + writeFile(t, filepath.Join(home, "network", "admin"), "tnsnames.ora", "X=(DESCRIPTION=(ADDRESS=(HOST=x)))") + if src, err := TNSFolder(home); err != nil || src.Entries[0].Alias != "X" { + t.Fatalf("home: %+v %v", src, err) + } + if src, err := TNSFolder(filepath.Join(dir, "tnsnames.ora")); err != nil || pathKey(src.Dir) != pathKey(dir) { + t.Fatalf("file: %+v %v", src, err) + } + if _, err := TNSFolder(filepath.Join(dir, "nowhere")); err == nil { + t.Fatal("folder without tnsnames.ora accepted") + } +} + +func TestTNSIFileCycleIsReported(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "tnsnames.ora", "A=(DESCRIPTION=(ADDRESS=(HOST=a)))\nIFILE=loop.ora\n") + writeFile(t, dir, "loop.ora", "IFILE=tnsnames.ora\n") + src, err := TNSFolder(dir) + if err != nil { + t.Fatal(err) + } + if src.Error == nil || !strings.Contains(*src.Error, "IFILE cycle") || len(src.Entries) != 1 { + t.Fatalf("source: %+v", src) + } +} + +func TestTNSSourceJSON(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "tnsnames.ora", "A=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1)))\n") + src, err := TNSFolder(dir) + if err != nil { + t.Fatal(err) + } + data, err := json.Marshal(src) + if err != nil { + t.Fatal(err) + } + var got map[string]any + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + for _, k := range []string{"dir", "label", "origin", "entries", "error"} { + if _, ok := got[k]; !ok { + t.Errorf("missing %s in %s", k, data) + } + } + entry := got["entries"].([]any)[0].(map[string]any) + for _, k := range []string{"alias", "descriptor", "host", "port", "serviceName", "sid", "protocol"} { + if _, ok := entry[k]; !ok { + t.Errorf("missing %s in %s", k, data) + } + } + if entry["port"] != float64(1) || entry["serviceName"] != nil { + t.Errorf("entry: %v", entry) + } + + empty, _ := json.Marshal(readSource(filepath.Join(dir, "none"), "x", "y")) + if !strings.Contains(string(empty), `"entries":[]`) { + t.Errorf("entries of an unreadable folder: %s", empty) + } +} + +func TestTNSCandidatesFromTheEnvironment(t *testing.T) { + root := t.TempDir() + instant := filepath.Join(root, "instantclient_23_5") + lib := "libclntsh.so.23.1" + if runtime.GOOS == "windows" { + lib = "oci.dll" + } + writeFile(t, instant, lib, "") + admin := filepath.Join(root, "admin") + env := func(name string) string { + switch name { + case "TNS_ADMIN": + return admin + case "ORACLE_HOME": + return filepath.Join(root, "product") + case "PATH": + return filepath.Join(root, "empty") + string(os.PathListSeparator) + instant + } + return "" + } + found := tnsCandidates(env) + if found[0].origin != "TNS_ADMIN" || found[0].dir != admin { + t.Fatalf("first: %+v", found[0]) + } + if found[1].origin != "ORACLE_HOME" || found[1].dir != filepath.Join(root, "product", "network", "admin") { + t.Fatalf("second: %+v", found[1]) + } + var instantFound, homeFound bool + for _, c := range found { + if c.origin == "Instant Client on PATH" && c.dir == filepath.Join(instant, "network", "admin") { + instantFound = true + } + if c.origin == "Oracle client on PATH" && c.dir == filepath.Join(root, "network", "admin") { + homeFound = true + } + if strings.Contains(c.dir, "empty") { + t.Errorf("folder without a client library: %+v", c) + } + } + if !instantFound || !homeFound { + t.Fatalf("PATH folders missing: %+v", found) + } +} + +func TestTNSSourcesFollowTNSAdmin(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "tnsnames.ora", "LQ_ONLY_HERE=(DESCRIPTION=(ADDRESS=(HOST=h)))\n") + t.Setenv("TNS_ADMIN", dir) + sources := TNSSources() + if len(sources) == 0 || pathKey(sources[0].Dir) != pathKey(dir) || sources[0].Origin != "TNS_ADMIN" { + t.Fatalf("sources: %+v", sources) + } + if descriptor, _, err := ResolveTNS("lq_only_here", ""); err != nil || !strings.Contains(descriptor, "HOST=h") { + t.Fatalf("resolve: %q %v", descriptor, err) + } + if defaultTNSDir() != sources[0].Dir { + t.Fatalf("default folder: %q", defaultTNSDir()) + } +} diff --git a/internal/drivers/oracle/tns_windows.go b/internal/drivers/oracle/tns_windows.go new file mode 100644 index 0000000..c2adb7f --- /dev/null +++ b/internal/drivers/oracle/tns_windows.go @@ -0,0 +1,56 @@ +//go:build windows + +package oracle + +import ( + "path/filepath" + "strings" + + "golang.org/x/sys/windows/registry" +) + +type registryHome struct { + dir, label, origin string +} + +// registryHomes lists the Oracle homes registered by Windows installers +// (HKLM\SOFTWARE\ORACLE\KEY_*). +func registryHomes() []registryHome { + var out []registryHome + for _, root := range []string{`SOFTWARE\ORACLE`, `SOFTWARE\WOW6432Node\ORACLE`} { + oracle, err := registry.OpenKey(registry.LOCAL_MACHINE, root, registry.READ) + if err != nil { + continue + } + if dir, _, err := oracle.GetStringValue("TNS_ADMIN"); err == nil { + out = append(out, registryHome{dir: dir, label: dir, origin: "Windows registry"}) + } + names, _ := oracle.ReadSubKeyNames(-1) + for _, name := range names { + if !strings.HasPrefix(strings.ToUpper(name), "KEY_") { + continue + } + key, err := registry.OpenKey(oracle, name, registry.READ) + if err != nil { + continue + } + homeName, _, err := key.GetStringValue("ORACLE_HOME_NAME") + if err != nil { + homeName = name[len("KEY_"):] + } + if dir, _, err := key.GetStringValue("TNS_ADMIN"); err == nil { + out = append(out, registryHome{dir: dir, label: homeName, origin: "Windows registry"}) + } + if home, _, err := key.GetStringValue("ORACLE_HOME"); err == nil { + out = append(out, registryHome{ + dir: filepath.Join(home, "network", "admin"), + label: homeName, + origin: "Oracle home", + }) + } + key.Close() + } + oracle.Close() + } + return out +} diff --git a/internal/drivers/oracle/values.go b/internal/drivers/oracle/values.go new file mode 100644 index 0000000..4aeba34 --- /dev/null +++ b/internal/drivers/oracle/values.go @@ -0,0 +1,369 @@ +package oracle + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + "strconv" + "strings" + "time" + + goora "github.com/sijms/go-ora/v2" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +// binaryPreviewBytes is how much of a binary value the grid shows. +const binaryPreviewBytes = 32 * 1024 + +// column is what the formatting needs from a result column description. +type column struct { + name string + dataType goora.TNSType + csForm int + // Precision and scale as the server describes them; go-ora reports a + // NUMBER without them as scale 0xFF. + precision int + scale int + maxLen int + charLen int + typeName string +} + +func columnOf(p *goora.ParameterInfo) column { + return column{ + name: p.Name, + dataType: p.DataType, + csForm: p.CharsetForm, + precision: int(p.Precision), + scale: int(p.Scale), + maxLen: p.MaxLen, + charLen: p.MaxCharLen, + typeName: p.TypeName, + } +} + +// oraName is the Oracle name of the column's type. +func (c column) oraName() string { + national := c.csForm == 2 + switch c.dataType { + case goora.NCHAR, goora.VARCHAR: + if national { + return "NVARCHAR2" + } + return "VARCHAR2" + case goora.CHAR, goora.CHARZ: + if national { + return "NCHAR" + } + return "CHAR" + case goora.NUMBER, goora.FLOAT, goora.VarNum: + return "NUMBER" + case goora.BInteger: + return "BINARY_INTEGER" + case goora.LONG, goora.LongVarChar: + return "LONG" + case goora.ROWID: + return "ROWID" + case goora.UROWID: + return "UROWID" + case goora.DATE, goora.OCIDate: + return "DATE" + case goora.RAW: + return "RAW" + case goora.LongRaw, goora.LongVarRaw: + return "LONG RAW" + case goora.IBFloat, goora.BFloat: + return "BINARY_FLOAT" + case goora.IBDouble, goora.BDouble: + return "BINARY_DOUBLE" + case goora.REFCURSOR, goora.RESULTSET: + return "CURSOR" + case goora.OCIClobLocator: + if national { + return "NCLOB" + } + return "CLOB" + case goora.OCIBlobLocator: + return "BLOB" + case goora.OCIFileLocator: + return "BFILE" + case goora.JSON: + return "JSON" + case goora.VECTOR: + return "VECTOR" + case goora.Boolean: + return "BOOLEAN" + case goora.TimeStampDTY, goora.TIMESTAMP: + return "TIMESTAMP" + case goora.TimeStampTZ_DTY, goora.TIMESTAMPTZ: + return "TIMESTAMP WITH TIME ZONE" + case goora.TimeStampLTZ_DTY, goora.TimeStampeLTZ: + return "TIMESTAMP WITH LOCAL TIME ZONE" + case goora.IntervalYM_DTY, goora.IntervalYM: + return "INTERVAL YEAR TO MONTH" + case goora.IntervalDS_DTY, goora.IntervalDS: + return "INTERVAL DAY TO SECOND" + case goora.XMLType, goora.OCIXMLType: + if strings.EqualFold(c.typeName, "XMLTYPE") { + return "XMLTYPE" + } + return "OBJECT" + } + return "UNKNOWN" +} + +// dataTypeName is the type as the grid shows it: VARCHAR2(30), NUMBER(10,2), +// TIMESTAMP(6)... +func (c column) dataTypeName() string { + switch c.dataType { + case goora.NCHAR, goora.VARCHAR, goora.CHAR, goora.CHARZ: + return fmt.Sprintf("%s(%d)", c.oraName(), c.charLen) + case goora.RAW: + return fmt.Sprintf("RAW(%d)", c.maxLen) + case goora.IntervalDS_DTY, goora.IntervalDS: + return fmt.Sprintf("INTERVAL DAY(%d) TO SECOND(%d)", c.precision, c.scale) + case goora.IntervalYM_DTY, goora.IntervalYM: + return fmt.Sprintf("INTERVAL YEAR(%d) TO MONTH", c.precision) + case goora.NUMBER: + switch { + case c.scale == 0xFF || c.precision == 0: + return "NUMBER" + case c.scale == 0: + return fmt.Sprintf("NUMBER(%d)", c.precision) + default: + return fmt.Sprintf("NUMBER(%d,%d)", c.precision, int8(c.scale)) + } + case goora.TimeStampDTY, goora.TIMESTAMP: + return fmt.Sprintf("TIMESTAMP(%d)", c.scale) + case goora.TimeStampLTZ_DTY, goora.TimeStampeLTZ: + return fmt.Sprintf("TIMESTAMP(%d) WITH LOCAL TIME ZONE", c.scale) + case goora.TimeStampTZ_DTY, goora.TIMESTAMPTZ: + return fmt.Sprintf("TIMESTAMP(%d) WITH TIME ZONE", c.scale) + } + return c.oraName() +} + +func (c column) kind() model.ValueKind { + switch c.dataType { + case goora.NUMBER, goora.BInteger, goora.FLOAT, goora.VarNum, + goora.IBFloat, goora.IBDouble, goora.BFloat, goora.BDouble: + return model.KindNumber + case goora.Boolean: + return model.KindBool + case goora.DATE, goora.OCIDate, goora.TimeStampDTY, goora.TIMESTAMP, + goora.TimeStampTZ_DTY, goora.TIMESTAMPTZ, goora.TimeStampLTZ_DTY, goora.TimeStampeLTZ, + goora.IntervalDS_DTY, goora.IntervalDS, goora.IntervalYM_DTY, goora.IntervalYM: + return model.KindTemporal + case goora.RAW, goora.LongRaw, goora.LongVarRaw, goora.OCIBlobLocator: + return model.KindBinary + case goora.JSON: + return model.KindJSON + case goora.CHAR, goora.CHARZ, goora.NCHAR, goora.VARCHAR, goora.LONG, goora.LongVarChar, + goora.ROWID, goora.UROWID, goora.OCIClobLocator: + return model.KindText + } + return model.KindOther +} + +// fractionDigits is the number of fractional second digits of a TIMESTAMP +// column. +func (c column) fractionDigits() int { + if c.scale < 0 || c.scale > 9 { + if c.scale == 0xFF { + return 0 + } + return 9 + } + return c.scale +} + +func columnInfos(cols []column) []model.ColumnInfo { + out := make([]model.ColumnInfo, len(cols)) + for i, c := range cols { + out[i] = model.ColumnInfo{Name: c.name, TypeName: c.dataTypeName(), Kind: c.kind()} + } + return out +} + +// formatValue turns a value from go-ora into the text the grid shows; nil is +// NULL. +func formatValue(ctx context.Context, c column, v driver.Value) *string { + if v == nil { + return nil + } + s := formatText(ctx, c, v) + return &s +} + +func formatText(ctx context.Context, c column, v driver.Value) string { + switch c.dataType { + case goora.TimeStampTZ_DTY, goora.TIMESTAMPTZ: + if t, ok := v.(time.Time); ok { + return formatTimestamp(t, c.fractionDigits(), true) + } + case goora.DATE, goora.OCIDate: + if t, ok := v.(time.Time); ok { + return formatTimestamp(t, 0, false) + } + case goora.TimeStampDTY, goora.TIMESTAMP, goora.TimeStampLTZ_DTY, goora.TimeStampeLTZ: + if t, ok := v.(time.Time); ok { + return formatTimestamp(t, c.fractionDigits(), false) + } + case goora.IntervalDS_DTY, goora.IntervalDS: + if s, ok := v.(string); ok { + return intervalDS(s) + } + case goora.IntervalYM_DTY, goora.IntervalYM: + if s, ok := v.(string); ok { + return intervalYM(s) + } + case goora.NUMBER, goora.BInteger, goora.FLOAT, goora.VarNum: + if s, ok := v.(string); ok { + return strings.TrimSuffix(s, ".") + } + case goora.VECTOR: + // INT8 vectors arrive as []uint8. + if b, ok := v.([]uint8); ok { + parts := make([]string, len(b)) + for i, n := range b { + parts[i] = strconv.Itoa(int(int8(n))) + } + return "[" + strings.Join(parts, ",") + "]" + } + } + switch x := v.(type) { + case string: + return x + case []byte: + return hexText(ctx, x) + case bool: + if x { + return "TRUE" + } + return "FALSE" + case float64: + return formatFloat(x, 64) + case float32: + return formatFloat(float64(x), 32) + case time.Time: + return formatTimestamp(x, c.fractionDigits(), false) + case int64: + return strconv.FormatInt(x, 10) + case []float32: + parts := make([]string, len(x)) + for i, f := range x { + parts[i] = formatFloat(float64(f), 32) + } + return "[" + strings.Join(parts, ",") + "]" + case []float64: + parts := make([]string, len(x)) + for i, f := range x { + parts[i] = formatFloat(f, 64) + } + return "[" + strings.Join(parts, ",") + "]" + case *goora.DataSet: + _ = x.Close() + return "(cursor)" + case goora.BFile, *goora.BFile: + return "(bfile)" + } + return "(" + c.dataTypeName() + ")" +} + +// formatFloat prints BINARY_FLOAT/DOUBLE with the special names Oracle uses. +func formatFloat(v float64, bits int) string { + switch { + case math.IsNaN(v): + return "Nan" + case math.IsInf(v, 1): + return "Inf" + case math.IsInf(v, -1): + return "-Inf" + } + return strconv.FormatFloat(v, 'f', -1, bits) +} + +// formatTimestamp prints `2024-05-01 13:45:00[.123][ +03:00]`, with the +// column's fractional digits. Values with a time zone arrive in the local +// time of their offset. +func formatTimestamp(t time.Time, digits int, withTZ bool) string { + var b strings.Builder + fmt.Fprintf(&b, "%04d-%02d-%02d %02d:%02d:%02d", t.Year(), int(t.Month()), t.Day(), t.Hour(), t.Minute(), t.Second()) + if digits > 9 { + digits = 9 + } + if digits > 0 { + frac := fmt.Sprintf("%09d", t.Nanosecond()) + b.WriteByte('.') + b.WriteString(frac[:digits]) + } + if withTZ { + _, offset := t.Zone() + sign := byte('+') + if offset < 0 { + sign = '-' + offset = -offset + } + fmt.Fprintf(&b, " %c%02d:%02d", sign, offset/3600, offset%3600/60) + } + return b.String() +} + +// intervalDS rewrites go-ora's `+DD HH:MI:SS.FFFFFF` as the ISO 8601 text the +// Oracle drivers print: `P3DT4H5M6.000000000S`, every part negative for a +// negative interval. +func intervalDS(s string) string { + if len(s) < 2 { + return s + } + negative := s[0] == '-' + var days, hours, minutes, seconds, micros int64 + if _, err := fmt.Sscanf(s[1:], "%d %d:%d:%d.%d", &days, &hours, &minutes, &seconds, µs); err != nil { + return s + } + nanos := micros * 1000 + if negative { + days, hours, minutes, seconds, nanos = -days, -hours, -minutes, -seconds, -nanos + } + return fmt.Sprintf("P%dDT%dH%dM%d.%09dS", days, hours, minutes, seconds, nanos) +} + +// intervalYM rewrites go-ora's `+YY-MM` as `P1Y2M`. +func intervalYM(s string) string { + if len(s) < 2 { + return s + } + negative := s[0] == '-' + var years, months int64 + if _, err := fmt.Sscanf(s[1:], "%d-%d", &years, &months); err != nil { + return s + } + if negative { + years, months = -years, -months + } + return fmt.Sprintf("P%dY%dM", years, months) +} + +// hexText is uppercase hexadecimal, the way SQL*Plus displays RAW, cut to +// the preview size unless ctx asks for full values. +func hexText(ctx context.Context, data []byte) string { + limit := drivers.BinaryLimit(ctx, binaryPreviewBytes) + shown := data + if len(shown) > limit { + shown = shown[:limit] + } + const digits = "0123456789ABCDEF" + var b strings.Builder + b.Grow(len(shown)*2 + 24) + for _, c := range shown { + b.WriteByte(digits[c>>4]) + b.WriteByte(digits[c&0x0F]) + } + if len(data) > len(shown) { + fmt.Fprintf(&b, "… (%d bytes)", len(data)) + } + return b.String() +} diff --git a/internal/drivers/redis/args.go b/internal/drivers/redis/args.go new file mode 100644 index 0000000..06cae85 --- /dev/null +++ b/internal/drivers/redis/args.go @@ -0,0 +1,173 @@ +package redis + +import ( + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// Argument parsing, with redis-cli's rules (sdssplitargs). + +func isSpace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r', 0x0b, 0x0c: + return true + } + return false +} + +func hexValue(c byte) (byte, bool) { + switch { + case c >= '0' && c <= '9': + return c - '0', true + case c >= 'a' && c <= 'f': + return c - 'a' + 10, true + case c >= 'A' && c <= 'F': + return c - 'A' + 10, true + } + return 0, false +} + +// splitArgs splits a command line into arguments the way redis-cli does: +// double quotes take \n \r \t \b \a \\ \" and \xHH, single quotes only \', +// and a closing quote must be followed by a space or the end. +func splitArgs(line string) ([][]byte, error) { + b := []byte(line) + invalidAt := func(message string, at int) error { + e := apperr.New(apperr.Invalid, message) + pos := utf8.RuneCountInString(line[:at]) + e.Position = &pos + return e + } + at := func(i int) (byte, bool) { + if i < len(b) { + return b[i], true + } + return 0, false + } + args := [][]byte{} + p := 0 + for { + for p < len(b) && isSpace(b[p]) { + p++ + } + if p >= len(b) { + return args, nil + } + current := []byte{} + inDouble, inSingle := false, false + quoteStart := 0 + word: + for { + switch { + case inDouble: + if p >= len(b) { + return nil, invalidAt("Unbalanced quotes in the command.", quoteStart) + } + next, hasNext := at(p + 1) + switch { + case b[p] == '\\' && hasNext && next == 'x': + hc, _ := at(p + 2) + lc, _ := at(p + 3) + hi, okHi := hexValue(hc) + lo, okLo := hexValue(lc) + if okHi && okLo { + current = append(current, hi*16+lo) + p += 3 + } else { + p++ + current = append(current, 'x') + } + case b[p] == '\\' && hasNext: + p++ + c := b[p] + switch c { + case 'n': + c = '\n' + case 'r': + c = '\r' + case 't': + c = '\t' + case 'b': + c = 0x08 + case 'a': + c = 0x07 + } + current = append(current, c) + case b[p] == '"': + if hasNext && !isSpace(next) { + return nil, invalidAt("A closing quote must be followed by a space.", p) + } + p++ + break word + default: + current = append(current, b[p]) + } + case inSingle: + if p >= len(b) { + return nil, invalidAt("Unbalanced quotes in the command.", quoteStart) + } + next, hasNext := at(p + 1) + switch { + case b[p] == '\\' && hasNext && next == '\'': + p++ + current = append(current, '\'') + case b[p] == '\'': + if hasNext && !isSpace(next) { + return nil, invalidAt("A closing quote must be followed by a space.", p) + } + p++ + break word + default: + current = append(current, b[p]) + } + case p >= len(b) || isSpace(b[p]): + break word + case b[p] == '"': + inDouble = true + quoteStart = p + case b[p] == '\'': + inSingle = true + quoteStart = p + default: + current = append(current, b[p]) + } + p++ + } + args = append(args, current) + } +} + +// argIs reports whether argument i is word, ignoring ASCII case. +func argIs(args [][]byte, i int, word string) bool { + return i < len(args) && equalFoldASCII(args[i], word) +} + +func equalFoldASCII(a []byte, word string) bool { + if len(a) != len(word) { + return false + } + for i := range a { + if upperASCII(a[i]) != upperASCII(word[i]) { + return false + } + } + return true +} + +func upperASCII(c byte) byte { + if c >= 'a' && c <= 'z' { + return c - 'a' + 'A' + } + return c +} + +// hasArg reports whether any argument after the command name is word. +func hasArg(args [][]byte, word string) bool { + for _, a := range args[min(1, len(args)):] { + if equalFoldASCII(a, word) { + return true + } + } + return false +} diff --git a/internal/drivers/redis/fake_test.go b/internal/drivers/redis/fake_test.go new file mode 100644 index 0000000..74255a2 --- /dev/null +++ b/internal/drivers/redis/fake_test.go @@ -0,0 +1,543 @@ +package redis + +// Session tests against a minimal in-process RESP server, so connection, +// command flow, state tracking and cancel run without a real Redis. + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +type fakeServer struct { + ln net.Listener + // handle returns the raw reply to a command; "" falls back to + // defaultReply. + handle func(args []string) string + + mu sync.Mutex + commands [][]byte // every command, its arguments joined by spaces + rawArgs [][][]byte + + blocked atomic.Int32 + unblocked chan struct{} +} + +func newFake(t *testing.T, handle func(args []string) string) *fakeServer { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + f := &fakeServer{ln: ln, handle: handle, unblocked: make(chan struct{}, 1)} + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go f.serve(c) + } + }() + return f +} + +func (f *fakeServer) port() uint16 { return uint16(f.ln.Addr().(*net.TCPAddr).Port) } + +func (f *fakeServer) profile() model.ConnectionProfile { + p := model.DefaultProfile() + p.Engine = model.Redis + p.Host = "127.0.0.1" + p.Port = f.port() + p.SslMode = model.SslDisable + return p +} + +func (f *fakeServer) serve(c net.Conn) { + defer c.Close() + r := bufio.NewReader(c) + for { + args, err := readCommand(r) + if err != nil { + // Not RESP (a TLS hello, for example): hang up. + return + } + texts := make([]string, len(args)) + for i, a := range args { + texts[i] = string(a) + } + f.mu.Lock() + f.commands = append(f.commands, []byte(strings.Join(texts, " "))) + f.rawArgs = append(f.rawArgs, args) + f.mu.Unlock() + reply := "" + if f.handle != nil { + reply = f.handle(texts) + } + if reply == "" { + reply = f.defaultReply(texts) + } + if _, err := io.WriteString(c, reply); err != nil { + return + } + } +} + +func readCommand(r *bufio.Reader) ([][]byte, error) { + line, err := r.ReadString('\n') + if err != nil || !strings.HasPrefix(line, "*") { + return nil, errors.New("not a command") + } + n, err := strconv.Atoi(strings.TrimSpace(line[1:])) + if err != nil { + return nil, err + } + args := make([][]byte, n) + for i := range args { + head, err := r.ReadString('\n') + if err != nil || !strings.HasPrefix(head, "$") { + return nil, errors.New("not a bulk string") + } + size, err := strconv.Atoi(strings.TrimSpace(head[1:])) + if err != nil { + return nil, err + } + buf := make([]byte, size+2) + if _, err := io.ReadFull(r, buf); err != nil { + return nil, err + } + args[i] = buf[:size] + } + return args, nil +} + +func bulkReply(s string) string { return fmt.Sprintf("$%d\r\n%s\r\n", len(s), s) } + +func (f *fakeServer) defaultReply(args []string) string { + name := strings.ToUpper(args[0]) + sub := "" + if len(args) > 1 { + sub = strings.ToUpper(args[1]) + } + switch { + case name == "HELLO": + return "%1\r\n$6\r\nserver\r\n$5\r\nredis\r\n" + case name == "CLIENT" && sub == "ID": + return ":7\r\n" + case name == "CLIENT" && sub == "UNBLOCK": + if f.blocked.Load() > 0 { + f.unblocked <- struct{}{} + return ":1\r\n" + } + return ":0\r\n" + case name == "BLPOP": + f.blocked.Add(1) + defer f.blocked.Add(-1) + select { + case <-f.unblocked: + return "-UNBLOCKED client unblocked via CLIENT UNBLOCK\r\n" + case <-time.After(10 * time.Second): + return "*-1\r\n" + } + case name == "INFO": + return bulkReply("# Server\r\nredis_version:7.4.1\r\n") + case name == "ACL" && sub == "WHOAMI": + return bulkReply("default") + case name == "PING": + return "+PONG\r\n" + case name == "CLIENT", name == "SELECT", name == "SET": + return "+OK\r\n" + } + return "-ERR unknown command '" + args[0] + "'\r\n" +} + +func (f *fakeServer) received() []string { + f.mu.Lock() + defer f.mu.Unlock() + out := make([]string, len(f.commands)) + for i, c := range f.commands { + out[i] = string(c) + } + return out +} + +func (f *fakeServer) hasCommand(cmd string) bool { + for _, c := range f.received() { + if c == cmd { + return true + } + } + return false +} + +func connectFake(t *testing.T, f *fakeServer, p model.ConnectionProfile, password *string) *Session { + t.Helper() + s, err := Connect(context.Background(), p, password) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func run(t *testing.T, s *Session, line string) *model.ExecResult { + t.Helper() + r, err := s.Execute(context.Background(), model.ExecRequest{SQL: line, MaxRows: 100}) + if err != nil { + t.Fatalf("%s: %v", line, err) + } + return r +} + +func runErr(t *testing.T, s *Session, line string) *apperr.Error { + t.Helper() + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: line, MaxRows: 100}) + if err == nil { + t.Fatalf("%s: no error", line) + } + return apperr.From(err) +} + +func first(r *model.ExecResult) string { + if len(r.Rows) == 0 || len(r.Rows[0]) == 0 || r.Rows[0][0] == nil { + return "" + } + return *r.Rows[0][0] +} + +func TestFakeSession(t *testing.T) { + f := newFake(t, func(args []string) string { + switch strings.ToUpper(args[0]) { + case "HGETALL": + return "%2\r\n$2\r\nf1\r\n$2\r\nv1\r\n$2\r\nf2\r\n:7\r\n" + case "GET": + return "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n" + case "MULTI": + return "+OK\r\n" + case "SET": + if len(args) > 1 && args[1] == "tx" { + return "+QUEUED\r\n" + } + case "EXEC": + return "*1\r\n+OK\r\n" + } + return "" + }) + p := f.profile() + p.Database = "3" + s := connectFake(t, f, p, nil) + eq(t, s.Engine(), model.Redis) + eq(t, s.ServerVersion(), "Redis 7.4.1") + eq(t, *s.CurrentSchema(), "db3") + eq(t, *s.CurrentUser(), "default") + eq(t, f.hasCommand("SELECT 3"), true) + eq(t, f.hasCommand("CLIENT SETNAME LowQuery"), true) + eq(t, s.TxState(), model.TxState{Autocommit: true}) + + // Arguments are sent as raw bytes. + r := run(t, s, `SET k "\xff"`) + eq(t, first(r), "OK") + f.mu.Lock() + last := f.rawArgs[len(f.rawArgs)-1] + f.mu.Unlock() + eq(t, last, [][]byte{[]byte("SET"), []byte("k"), {0xff}}) + + r = run(t, s, "hgetall h") + eq(t, len(r.Columns), 2) + eq(t, r.Columns[0].Name, "field") + eq(t, *r.Rows[1][1], "7") + eq(t, r.Notices, []string{}) + + for _, line := range []string{"# comment", "// comment", " "} { + r = run(t, s, line) + if r.Columns != nil || len(r.Rows) != 0 { + t.Fatalf("%q: %+v", line, r) + } + } + e := runErr(t, s, "subscribe news") + eq(t, e.Kind, apperr.Invalid) + eq(t, e.Message, "SUBSCRIBE is not supported in the query editor.") + eq(t, runErr(t, s, "CLIENT REPLY OFF").Message, "CLIENT REPLY is not supported in the query editor.") + eq(t, runErr(t, s, `GET "abc`).Kind, apperr.Invalid) + + e = runErr(t, s, "GET k") + eq(t, e.Kind, apperr.Database) + eq(t, e.Code, "WRONGTYPE") + + if _, err := s.SetAutocommit(context.Background(), false); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("set autocommit off: %v", err) + } + if st, err := s.SetAutocommit(context.Background(), true); err != nil || !st.Autocommit { + t.Fatalf("set autocommit on: %v %v", st, err) + } + + eq(t, run(t, s, "MULTI").InTransaction, true) + r = run(t, s, "SET tx 1") + eq(t, first(r), "QUEUED") + eq(t, r.InTransaction, true) + if _, err := s.ListSchemas(context.Background()); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("list schemas in MULTI: %v", err) + } + st, err := s.EndTransaction(context.Background(), true) + if err != nil || st.InTransaction { + t.Fatalf("exec: %v %v", st, err) + } + // Nothing to end. + if st, err := s.EndTransaction(context.Background(), false); err != nil || st.InTransaction { + t.Fatalf("discard: %v %v", st, err) + } + + cols, err := s.ListColumns(context.Background(), "db0", "k") + if err != nil || cols == nil || len(cols) != 0 { + t.Fatalf("list columns: %v %v", cols, err) + } + if _, err := s.ObjectDDL(context.Background(), "db0", "k", "string"); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("object ddl: %v", err) + } + if _, err := s.ApplyChanges(context.Background(), model.ApplyRequest{}); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("apply changes: %v", err) + } + if _, err := s.Stream(context.Background(), "GET k", nil); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("stream: %v", err) + } +} + +func TestFakeListsDatabasesAndKeys(t *testing.T) { + f := newFake(t, func(args []string) string { + cmd := strings.ToUpper(strings.Join(args, " ")) + switch { + case cmd == "INFO KEYSPACE": + return bulkReply("# Keyspace\r\ndb0:keys=1\r\ndb5:keys=2\r\n") + case cmd == "CONFIG GET DATABASES": + return "%1\r\n$9\r\ndatabases\r\n$2\r\n16\r\n" + case cmd == "SCAN 0 COUNT 500": + return "*2\r\n$1\r\n9\r\n*2\r\n$1\r\nb\r\n$1\r\na\r\n" + case cmd == "SCAN 9 COUNT 500": + return "*2\r\n$1\r\n0\r\n*3\r\n$1\r\nc\r\n$1\r\na\r\n$1\r\n\xff\r\n" + case args[0] == "TYPE": + switch args[1] { + case "a": + return "+string\r\n" + case "b": + return "+hash\r\n" + case "\xff": + return "+ReJSON-RL\r\n" + } + return "+none\r\n" + } + return "" + }) + s := connectFake(t, f, f.profile(), nil) + schemas, err := s.ListSchemas(context.Background()) + if err != nil { + t.Fatal(err) + } + eq(t, len(schemas), 16) + eq(t, schemas[:4], []string{"db0", "db5", "db1", "db2"}) + + objects, err := s.ListObjects(context.Background(), "db5") + if err != nil { + t.Fatal(err) + } + eq(t, objects, []model.DbObject{ + {Name: "b", Kind: "hash"}, + {Name: `"\xff"`, Kind: "json"}, + {Name: "a", Kind: "string"}, + }) + got := f.received() + eq(t, f.hasCommand("SELECT 5"), true) + // The session is back on its own database. + eq(t, got[len(got)-1], "SELECT 0") + + if _, err := s.ListObjects(context.Background(), "nope"); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("unknown database: %v", err) + } +} + +func TestFakeAuthErrors(t *testing.T) { + // RESP3 server: HELLO and AUTH answer WRONGPASS. + f := newFake(t, func(args []string) string { + switch strings.ToUpper(args[0]) { + case "HELLO", "AUTH": + return "-WRONGPASS invalid username-password pair or user is disabled.\r\n" + } + return "" + }) + p := f.profile() + p.User = "lq_test" + _, err := Connect(context.Background(), p, model.Str("wrong")) + e := apperr.From(err) + eq(t, e.Kind, apperr.Connection) + eq(t, e.Code, "WRONGPASS") + + // RESP2 server (no HELLO): AUTH answers ERR. + f = newFake(t, func(args []string) string { + switch strings.ToUpper(args[0]) { + case "HELLO": + return "-ERR unknown command 'HELLO'\r\n" + case "AUTH": + return "-ERR invalid password\r\n" + } + return "" + }) + _, err = Connect(context.Background(), f.profile(), model.Str("wrong")) + e = apperr.From(err) + eq(t, e.Kind, apperr.Connection) + eq(t, e.Code, "WRONGPASS") + eq(t, e.Message, "Invalid username or password.") + + // A password is required and none was given. + f = newFake(t, func(args []string) string { + switch strings.ToUpper(args[0]) { + case "HELLO": + return "-NOAUTH HELLO must be called with the client already authenticated\r\n" + case "AUTH": + return "-ERR should not be sent\r\n" + case "CLIENT", "INFO", "ACL", "SELECT": + return "-NOAUTH Authentication required.\r\n" + } + return "" + }) + _, err = Connect(context.Background(), f.profile(), nil) + e = apperr.From(err) + eq(t, e.Kind, apperr.Connection) + eq(t, e.Code, "NOAUTH") + + p = f.profile() + p.Database = "x" + _, err = Connect(context.Background(), p, nil) + eq(t, apperr.From(err).Kind, apperr.Invalid) + + // Nobody listening. + ln, _ := net.Listen("tcp", "127.0.0.1:0") + p.Database = "" + p.Port = uint16(ln.Addr().(*net.TCPAddr).Port) + _ = ln.Close() + _, err = Connect(context.Background(), p, nil) + eq(t, apperr.From(err).Kind, apperr.Connection) +} + +func TestFakePreferFallsBackToPlain(t *testing.T) { + f := newFake(t, nil) + p := f.profile() + p.SslMode = model.SslPrefer + p.Database = "2" + started := time.Now() + s := connectFake(t, f, p, nil) + if time.Since(started) > 10*time.Second { + t.Fatalf("prefer took %v", time.Since(started)) + } + eq(t, *s.CurrentSchema(), "db2") + eq(t, first(run(t, s, "PING")), "PONG") +} + +// waitBlocked waits until the fake server holds a blocking command. +func waitBlocked(t *testing.T, f *fakeServer) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for f.blocked.Load() == 0 { + if time.Now().After(deadline) { + t.Fatal("the command never blocked") + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestFakeCancelsABlockingCommand(t *testing.T) { + f := newFake(t, func(args []string) string { + if strings.ToUpper(args[0]) == "DEBUG" { + time.Sleep(500 * time.Millisecond) + return "+OK\r\n" + } + return "" + }) + s := connectFake(t, f, f.profile(), nil) + + // Nothing running: nothing to do. + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "BLPOP lq:never 30", MaxRows: 10}) + done <- err + }() + waitBlocked(t, f) + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + e := apperr.From(<-done) + eq(t, e.Kind, apperr.Cancelled) + eq(t, e.Code, "UNBLOCKED") + eq(t, f.hasCommand("CLIENT UNBLOCK 7 ERROR"), true) + eq(t, first(run(t, s, "PING")), "PONG") + + // Cancelling the context interrupts the command too. + ctx, cancel := context.WithCancel(context.Background()) + go func() { + _, err := s.Execute(ctx, model.ExecRequest{SQL: "BLPOP lq:never 30", MaxRows: 10}) + done <- err + }() + waitBlocked(t, f) + cancel() + e = apperr.From(<-done) + eq(t, e.Kind, apperr.Cancelled) + eq(t, e.Code, "UNBLOCKED") + + // A command that does not block cannot be interrupted. + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "DEBUG SLEEP 0.5", MaxRows: 10}) + done <- err + }() + deadline := time.Now().Add(5 * time.Second) + for !s.busy.Load() && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + e = apperr.From(s.Cancel(context.Background())) + if e == nil || e.Kind != apperr.Invalid || e.Message != notBlocking { + t.Fatalf("cancel of a non-blocking command: %v", e) + } + if err := <-done; err != nil { + t.Fatal(err) + } + + // A cancelled context stops before sending. + _, err := s.Execute(ctx, model.ExecRequest{SQL: "PING"}) + eq(t, apperr.From(err).Kind, apperr.Cancelled) +} + +func TestFakeCloseInterruptsACommand(t *testing.T) { + f := newFake(t, nil) + s, err := Connect(context.Background(), f.profile(), nil) + if err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "BLPOP lq:never 30", MaxRows: 10}) + done <- err + }() + waitBlocked(t, f) + started := time.Now() + _ = s.Close() + err = <-done + if err == nil || time.Since(started) > 5*time.Second { + t.Fatalf("close: %v after %v", err, time.Since(started)) + } + eq(t, apperr.From(err).Kind, apperr.Connection) + eq(t, s.TxState().InTransaction, false) +} diff --git a/internal/drivers/redis/integration_test.go b/internal/drivers/redis/integration_test.go new file mode 100644 index 0000000..a4e8f13 --- /dev/null +++ b/internal/drivers/redis/integration_test.go @@ -0,0 +1,336 @@ +package redis + +// Tests against a real server. They only run with LQ_REDIS_HOST set (and +// optionally LQ_REDIS_PORT, default 6379, and LQ_REDIS_PASSWORD). + +import ( + "context" + "os" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func redisProfile(t *testing.T) (model.ConnectionProfile, *string) { + t.Helper() + host := os.Getenv("LQ_REDIS_HOST") + if host == "" { + t.Skip("LQ_REDIS_HOST is not set") + } + p := model.DefaultProfile() + p.Name = "test" + p.Engine = model.Redis + p.Host = host + p.Port = defaultPort + if port, err := strconv.ParseUint(os.Getenv("LQ_REDIS_PORT"), 10, 16); err == nil { + p.Port = uint16(port) + } + p.SslMode = model.SslDisable + var password *string + if pw := os.Getenv("LQ_REDIS_PASSWORD"); pw != "" { + password = &pw + } + return p, password +} + +func redisSession(t *testing.T) *Session { + t.Helper() + p, password := redisProfile(t) + s, err := Connect(context.Background(), p, password) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func execRows(t *testing.T, s *Session, line string, maxRows int) *model.ExecResult { + t.Helper() + r, err := s.Execute(context.Background(), model.ExecRequest{SQL: line, MaxRows: maxRows}) + if err != nil { + t.Fatalf("%s: %v", line, err) + } + return r +} + +func columnNames(r *model.ExecResult) []string { + out := make([]string, len(r.Columns)) + for i, c := range r.Columns { + out[i] = c.Name + } + return out +} + +// rowTexts shows a row with NULL as "". +func rowTexts(row model.Row) []string { + out := make([]string, len(row)) + for i, v := range row { + if v == nil { + out[i] = "" + } else { + out[i] = *v + } + } + return out +} + +func TestRedisConnectsAndReportsVersion(t *testing.T) { + s := redisSession(t) + v := s.ServerVersion() + if !strings.HasPrefix(v, "Redis ") && !strings.HasPrefix(v, "Valkey ") { + t.Fatalf("version: %s", v) + } + eq(t, *s.CurrentSchema(), "db0") + if s.CurrentUser() == nil { + t.Fatal("no current user") + } + eq(t, s.TxState(), model.TxState{Autocommit: true}) + if run(t, s, "# comment").Columns != nil || run(t, s, "// comment").Columns != nil { + t.Fatal("a comment returned columns") + } + eq(t, first(run(t, s, "PING")), "PONG") + + // prefer falls back to plain TCP on a server without TLS. + p, password := redisProfile(t) + p.SslMode = model.SslPrefer + p.Database = "2" + started := time.Now() + ps, err := Connect(context.Background(), p, password) + if err != nil { + t.Fatalf("prefer: %v", err) + } + defer ps.Close() + if time.Since(started) > 10*time.Second { + t.Fatalf("prefer took %v", time.Since(started)) + } + eq(t, *ps.CurrentSchema(), "db2") + + // ACL user: right and wrong password. + run(t, s, "ACL SETUSER lq_test on >lq-secret ~* &* +@all") + defer run(t, s, "ACL DELUSER lq_test") + p.SslMode = model.SslDisable + p.User = "lq_test" + u, err := Connect(context.Background(), p, model.Str("lq-secret")) + if err != nil { + t.Fatalf("acl user: %v", err) + } + defer u.Close() + eq(t, *u.CurrentUser(), "lq_test") + _, err = Connect(context.Background(), p, model.Str("wrong")) + if err == nil { + t.Fatal("connected with a wrong password") + } + e := apperr.From(err) + eq(t, e.Kind, apperr.Connection) + eq(t, e.Code, "WRONGPASS") +} + +func TestRedisSetsAndGetsStrings(t *testing.T) { + s := redisSession(t) + eq(t, first(run(t, s, `SET "lq:t:str key" "a b\n"`)), "OK") + r := run(t, s, `GET "lq:t:str key"`) + eq(t, first(r), "a b\n") + eq(t, r.Columns[0].Name, "value") + run(t, s, `SET lq:t:bin "\xff\x00ok"`) + eq(t, first(run(t, s, "GET lq:t:bin")), `"\xff\x00ok"`) + eq(t, first(run(t, s, "GET lq:t:missing")), "") + r = run(t, s, "INCRBY lq:t:n 5") + eq(t, r.Columns[0].Kind, model.KindNumber) + run(t, s, `DEL lq:t:n "lq:t:str key" lq:t:bin`) + + eq(t, runErr(t, s, `GET "abc`).Kind, apperr.Invalid) +} + +func TestRedisHashesAndSortedSetsHaveColumns(t *testing.T) { + s := redisSession(t) + run(t, s, "DEL lq:t:h lq:t:z") + run(t, s, `HSET lq:t:h f1 v1 f2 "v 2"`) + r := run(t, s, "HGETALL lq:t:h") + eq(t, columnNames(r), []string{"field", "value"}) + rows := make([][]string, len(r.Rows)) + for i, row := range r.Rows { + rows[i] = rowTexts(row) + } + slices.SortFunc(rows, func(a, b []string) int { return strings.Compare(a[0], b[0]) }) + eq(t, rows[1], []string{"f2", "v 2"}) + + run(t, s, "ZADD lq:t:z 1 a 2.5 b") + r = run(t, s, "ZRANGE lq:t:z 0 -1 WITHSCORES") + eq(t, columnNames(r), []string{"member", "score"}) + eq(t, r.Columns[1].Kind, model.KindNumber) + eq(t, rowTexts(r.Rows[1]), []string{"b", "2.5"}) + + e := runErr(t, s, "LPUSH lq:t:h x") + eq(t, e.Kind, apperr.Database) + eq(t, e.Code, "WRONGTYPE") + run(t, s, "DEL lq:t:h lq:t:z") +} + +func TestRedisLimitsRowsAndParsesInfo(t *testing.T) { + s := redisSession(t) + run(t, s, "DEL lq:t:list") + values := make([]string, 50) + for i := range values { + values[i] = strconv.Itoa(i + 1) + } + run(t, s, "RPUSH lq:t:list "+strings.Join(values, " ")) + r := execRows(t, s, "LRANGE lq:t:list 0 -1", 10) + eq(t, len(r.Rows), 10) + eq(t, r.Truncated, true) + eq(t, rowTexts(r.Rows[9]), []string{"10", "10"}) + r = execRows(t, s, "LRANGE lq:t:list 0 -1", 0) + eq(t, len(r.Rows), 50) + eq(t, r.Truncated, false) + run(t, s, "DEL lq:t:list") + + r = run(t, s, "INFO server") + eq(t, columnNames(r), []string{"section", "key", "value"}) + found := slices.ContainsFunc(r.Rows, func(row model.Row) bool { + texts := rowTexts(row) + return texts[0] == "Server" && texts[1] == "redis_version" + }) + if !found { + t.Fatal("INFO server has no redis_version row") + } +} + +func TestRedisListsDatabasesAndKeys(t *testing.T) { + s := redisSession(t) + run(t, s, "SET lq:t:home here") + run(t, s, "SELECT 9") + for _, line := range []string{ + "DEL lq:obj:str lq:obj:hash lq:obj:list lq:obj:set lq:obj:zset lq:obj:stream", + "SET lq:obj:str v", + "HSET lq:obj:hash f v", + "RPUSH lq:obj:list a", + "SADD lq:obj:set a", + "ZADD lq:obj:zset 1 a", + "XADD lq:obj:stream * f v", + } { + run(t, s, line) + } + schemas, err := s.ListSchemas(context.Background()) + if err != nil { + t.Fatal(err) + } + eq(t, schemas[0], "db9") + run(t, s, "SELECT 0") + schemas, err = s.ListSchemas(context.Background()) + if err != nil { + t.Fatal(err) + } + eq(t, schemas[0], "db0") + + objects, err := s.ListObjects(context.Background(), "db9") + if err != nil { + t.Fatal(err) + } + kind := func(name string) string { + for _, o := range objects { + if o.Name == name { + return o.Kind + } + } + return "" + } + eq(t, kind("lq:obj:str"), "string") + eq(t, kind("lq:obj:hash"), "hash") + eq(t, kind("lq:obj:list"), "list") + eq(t, kind("lq:obj:set"), "set") + eq(t, kind("lq:obj:zset"), "zset") + eq(t, kind("lq:obj:stream"), "stream") + sorted := slices.IsSortedFunc(objects, func(a, b model.DbObject) int { + if c := strings.Compare(a.Kind, b.Kind); c != 0 { + return c + } + return strings.Compare(a.Name, b.Name) + }) + if !sorted { + t.Fatal("objects are not sorted by kind and name") + } + // The session is back on its own database. + eq(t, first(run(t, s, "GET lq:t:home")), "here") + cols, err := s.ListColumns(context.Background(), "db9", "lq:obj:str") + if err != nil || len(cols) != 0 { + t.Fatalf("list columns: %v %v", cols, err) + } + run(t, s, "DEL lq:t:home") +} + +func TestRedisTracksTransactions(t *testing.T) { + s := redisSession(t) + ctx := context.Background() + _, err := s.SetAutocommit(ctx, false) + eq(t, apperr.From(err).Kind, apperr.Invalid) + st, err := s.SetAutocommit(ctx, true) + if err != nil || !st.Autocommit { + t.Fatalf("autocommit on: %v %v", st, err) + } + + eq(t, run(t, s, "MULTI").InTransaction, true) + r := run(t, s, "SET lq:t:tx 1") + eq(t, first(r), "QUEUED") + eq(t, r.InTransaction && s.TxState().InTransaction, true) + r = run(t, s, "EXEC") + eq(t, r.InTransaction || s.TxState().InTransaction, false) + eq(t, *r.Rows[0][1], "OK") + + run(t, s, "MULTI") + run(t, s, "SET lq:t:tx 2") + st, err = s.EndTransaction(ctx, false) + if err != nil || st.InTransaction { + t.Fatalf("discard: %v %v", st, err) + } + eq(t, first(run(t, s, "GET lq:t:tx")), "1") + + run(t, s, "MULTI") + e := runErr(t, s, "NOSUCHCOMMAND") + eq(t, e.Code, "ERR") + eq(t, s.TxState().InTransaction, true) + _, err = s.EndTransaction(ctx, true) + eq(t, apperr.From(err).Code, "EXECABORT") + eq(t, s.TxState().InTransaction, false) + run(t, s, "DEL lq:t:tx") +} + +func TestRedisCancelsABlockingCommand(t *testing.T) { + s := redisSession(t) + started := time.Now() + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "BLPOP lq:never 30", MaxRows: 10}) + done <- err + }() + time.Sleep(time.Second) + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + e := apperr.From(<-done) + eq(t, e.Kind, apperr.Cancelled) + eq(t, e.Code, "UNBLOCKED") + if time.Since(started) > 15*time.Second { + t.Fatalf("cancel took %v", time.Since(started)) + } + eq(t, first(run(t, s, "PING")), "PONG") + // Nothing running: nothing to do. + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + + // Cancelling the context interrupts the command too. + ctx, cancel := context.WithCancel(context.Background()) + go func() { + _, err := s.Execute(ctx, model.ExecRequest{SQL: "BLPOP lq:never 30", MaxRows: 10}) + done <- err + }() + time.Sleep(time.Second) + cancel() + e = apperr.From(<-done) + eq(t, e.Kind, apperr.Cancelled) + eq(t, first(run(t, s, "PING")), "PONG") +} diff --git a/internal/drivers/redis/redis.go b/internal/drivers/redis/redis.go new file mode 100644 index 0000000..b9fd7a7 --- /dev/null +++ b/internal/drivers/redis/redis.go @@ -0,0 +1,847 @@ +// Package redis is the Redis (and Valkey) session, over go-redis. +// +// - Each Execute call is one command written like redis-cli input, split +// with redis-cli's rules (sdssplitargs) and sent as raw arguments. +// - The connection speaks RESP3 so maps, sets, doubles and booleans keep +// their types; servers without HELLO (Redis < 6) fall back to RESP2. +// Replies are read as raw RESP and parsed here (reply.go), which keeps +// map order and binary strings. +// - Replies become a table: scalars one value cell, maps field/value, +// arrays #/value (or one column per element of uniform tuples), INFO +// section/key/value. Nested values are compact JSON-like text and binary +// strings use redis-cli escapes ("\xff"), so nothing is lossy. +// - Redis has no autocommit mode: the transaction state is MULTI, tracked +// by command name. +// - Cancel runs CLIENT UNBLOCK ERROR over a short-lived second +// connection, which only interrupts blocking commands. +package redis + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "net" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + goredis "github.com/redis/go-redis/v9" + "github.com/redis/go-redis/v9/maintnotifications" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + defaultPort = 6379 + connectTimeout = 15 * time.Second + // preferTLSTimeout bounds the TLS attempt of prefer: a plain server may + // wait for a line that never comes, so the attempt gives up early and + // falls back to plain TCP. + preferTLSTimeout = 5 * time.Second + writeTimeout = 30 * time.Second + // MaxKeys is the number of keys listed per database in the tree. + MaxKeys = 1000 + scanCount = 500 +) + +const ( + notBlocking = "Redis can only interrupt blocking commands such as BLPOP or XREAD." + closedMessage = "The connection to the server was closed." +) + +// unsupported lists commands that would leave the connection in a mode +// where replies no longer match requests. +var unsupported = map[string]bool{ + "SUBSCRIBE": true, + "PSUBSCRIBE": true, + "SSUBSCRIBE": true, + "MONITOR": true, + "SYNC": true, + "PSYNC": true, +} + +// state is what the server keeps per connection that the session tracks. +type state struct { + // Between MULTI and EXEC/DISCARD. + inMulti bool + // Logical database selected on the connection. + db int64 + // SELECT queued inside MULTI, applied when EXEC runs. + queuedSelect *int64 +} + +// Session is one Redis connection. +type Session struct { + // mu serializes every call except Cancel. + mu sync.Mutex + client *goredis.Client + conn *goredis.Conn + // Where and how the session connected, reused by Cancel. + target target + tls *tls.Config + + clientID *int64 + busy atomic.Bool + + stateMu sync.Mutex + state state + + serverVersion string + currentUser *string + currentSchema *string +} + +var _ drivers.Session = (*Session)(nil) + +type target struct { + addr string + user string + password string +} + +// options builds the client options: RESP3, one connection, no read +// timeout (blocking commands may wait as long as they ask) and no retries. +func (t target) options(tlsConfig *tls.Config, dialTimeout time.Duration) *goredis.Options { + opt := &goredis.Options{ + Addr: t.addr, + Username: t.user, + Password: t.password, + Protocol: 3, + DialTimeout: dialTimeout, + DialerRetries: 1, + ReadTimeout: -1, + WriteTimeout: writeTimeout, + ContextTimeoutEnabled: true, + PoolSize: 1, + MaxRetries: -1, + ConnMaxIdleTime: -1, + ConnMaxLifetime: -1, + DisableIdentity: true, + MaintNotificationsConfig: &maintnotifications.Config{ + Mode: maintnotifications.ModeDisabled, + }, + } + if tlsConfig != nil { + opt.TLSConfig = tlsConfig.Clone() + } + return opt +} + +// Connect opens a session. password nil means none. +func Connect(ctx context.Context, profile model.ConnectionProfile, password *string) (*Session, error) { + db, ok := parseDB(profile.Database) + if !ok { + return nil, apperr.New(apperr.Invalid, "The database must be a number (0, 1, 2...).") + } + host := strings.TrimSpace(profile.Host) + port := profile.Port + if port == 0 { + port = defaultPort + } + t := target{ + addr: net.JoinHostPort(host, strconv.Itoa(int(port))), + user: strings.TrimSpace(profile.User), + } + if password != nil { + t.password = *password + } + + lenient := &tls.Config{ServerName: host, InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} + var ( + s *Session + err error + ) + switch profile.SslMode { + case model.SslDisable: + s, err = open(ctx, t, nil, connectTimeout) + case model.SslRequire: + s, err = open(ctx, t, lenient, connectTimeout) + case model.SslVerifyFull: + s, err = open(ctx, t, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}, connectTimeout) + default: + s, err = open(ctx, t, lenient, preferTLSTimeout) + if err != nil && !isServerReply(err) && ctx.Err() == nil { + s, err = open(ctx, t, nil, connectTimeout) + } + } + if err != nil { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + return nil, connectError(err) + } + if err := s.setup(ctx, db); err != nil { + _ = s.close() + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + return nil, err + } + return s, nil +} + +// open connects and runs the handshake (HELLO, or AUTH on RESP2 servers) +// along with CLIENT ID, whose reply is kept for Cancel. +func open(ctx context.Context, t target, tlsConfig *tls.Config, timeout time.Duration) (*Session, error) { + client := goredis.NewClient(t.options(tlsConfig, timeout)) + conn := client.EphemeralConn() + cctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + // The raw reply holds error replies to CLIENT ID itself (NOPERM, + // NOAUTH), which setup reports; err is a failed connection or + // handshake. + raw, err := conn.DoRaw(cctx, "CLIENT", "ID").Result() + if err != nil { + _ = conn.Close() + _ = client.Close() + if isServerReply(err) { + // Only the handshake can fail with a reply: HELLO, then AUTH. + err = authFailed{err} + } + return nil, err + } + s := &Session{client: client, conn: conn, target: t, tls: tlsConfig} + if v, perr := parseReply(raw); perr == nil && v.typ == vInt { + id := v.i + s.clientID = &id + } + return s, nil +} + +// setup names the client, selects the database and reads the version and +// user. Errors here are connection errors; NOAUTH and WRONGPASS keep their +// code. +func (s *Session) setup(ctx context.Context, db int64) error { + ctx, cancel := context.WithTimeout(ctx, connectTimeout) + defer cancel() + _, _ = s.call(ctx, "CLIENT", "SETNAME", "LowQuery") + if db != 0 { + if _, err := s.call(ctx, "SELECT", strconv.FormatInt(db, 10)); err != nil { + return asConnection(err) + } + } + info := "" + v, err := s.call(ctx, "INFO", "server") + if err != nil { + if e := apperr.From(err); e.Kind == apperr.Connection || isAuthCode(e) { + return asConnection(err) + } + } else { + info, _ = textOf(v) + } + if v, err := s.call(ctx, "ACL", "WHOAMI"); err == nil { + if user, ok := textOf(v); ok { + s.currentUser = &user + } + } + s.state = state{db: db} + s.serverVersion = productVersion(info) + s.currentSchema = model.Str("db" + strconv.FormatInt(db, 10)) + return nil +} + +// parseDB reads a database index: "" is 0, "3" or "db3" is 3. +func parseDB(text string) (int64, bool) { + t := strings.TrimSpace(text) + if t == "" { + return 0, true + } + digits := t + if len(t) > 2 && strings.EqualFold(t[:2], "db") { + digits = t[2:] + } + n, err := strconv.ParseInt(digits, 10, 64) + if err != nil || n < 0 { + return 0, false + } + return n, true +} + +// productVersion reads "Redis 7.4.1", "Valkey 8.1.0" or "Dragonfly 1.27.1" +// from INFO server. +func productVersion(info string) string { + field := func(name string) (string, bool) { + for _, l := range lines(info) { + k, v, ok := strings.Cut(strings.TrimSpace(l), ":") + if ok && k == name { + return strings.TrimSpace(v), true + } + } + return "", false + } + redisVersion, _ := field("redis_version") + valkey, isValkey := field("valkey_version") + if name, _ := field("server_name"); isValkey || name == "valkey" { + if !isValkey { + valkey = redisVersion + } + return strings.TrimRight("Valkey "+valkey, " ") + } + if v, ok := field("dragonfly_version"); ok { + return "Dragonfly " + strings.TrimPrefix(v, "df-v") + } + return strings.TrimRight("Redis "+redisVersion, " ") +} + +func (s *Session) Engine() model.Engine { return model.Redis } +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) TxState() model.TxState { + s.stateMu.Lock() + defer s.stateMu.Unlock() + return model.TxState{Autocommit: true, InTransaction: s.state.inMulti} +} + +func (s *Session) db() int64 { + s.stateMu.Lock() + defer s.stateMu.Unlock() + return s.state.db +} + +// rawCall sends one command and parses its reply. Error replies are +// values here; err is a transport failure. +func rawCall(ctx context.Context, conn *goredis.Conn, args ...any) (value, error) { + raw, err := conn.DoRaw(ctx, args...).Result() + if err != nil { + return value{}, err + } + v, err := parseReply(raw) + if err != nil { + return value{}, apperr.Connectionf("Invalid reply from the server: %v", err) + } + return v, nil +} + +// call sends one command; an error reply becomes an error. The command is +// not cancelled with ctx (only its deadline applies), so a reply is never +// left unread on the connection. +func (s *Session) call(ctx context.Context, args ...any) (value, error) { + v, err := rawCall(ctx, s.conn, args...) + if err != nil { + return value{}, mapError(err) + } + if v.typ == vError { + return value{}, serverError(v) + } + return v, nil +} + +// detached is ctx without its cancellation and deadline: a reply cut off +// halfway would leave the connection out of step, so cancellation goes +// through CLIENT UNBLOCK instead. +func detached(ctx context.Context) context.Context { return context.WithoutCancel(ctx) } + +// watch interrupts a blocking command when ctx is done before the +// returned stop is called. +func (s *Session) watch(ctx context.Context) (stop func()) { + if ctx.Done() == nil { + return func() {} + } + done := make(chan struct{}) + finished := make(chan struct{}) + go func() { + defer close(finished) + select { + case <-done: + case <-ctx.Done(): + _ = s.unblock(context.Background()) + } + }() + return func() { + close(done) + <-finished + } +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + text := strings.TrimSpace(req.SQL) + var args [][]byte + if !strings.HasPrefix(text, "#") && !strings.HasPrefix(text, "//") { + var err error + if args, err = splitArgs(req.SQL); err != nil { + return nil, err + } + } + if len(args) == 0 { + r := &model.ExecResult{InTransaction: s.TxState().InTransaction} + r.Normalize() + return r, nil + } + name := commandName(args[0]) + replyOff := name == "CLIENT" && argIs(args, 1, "REPLY") + if unsupported[name] || replyOff { + if replyOff { + name = "CLIENT REPLY" + } + return nil, apperr.Invalidf("%s is not supported in the query editor.", name) + } + cmd := make([]any, len(args)) + for i, a := range args { + cmd[i] = a + } + + s.mu.Lock() + if ctx.Err() != nil { + s.mu.Unlock() + return nil, apperr.CancelledErr() + } + s.busy.Store(true) + stop := s.watch(ctx) + started := time.Now() + reply, err := rawCall(detached(ctx), s.conn, cmd...) + elapsed := time.Since(started) + s.busy.Store(false) + stop() + s.track(name, args, reply, err) + s.mu.Unlock() + + if err != nil { + return nil, mapError(err) + } + if reply.typ == vError { + return nil, serverError(reply) + } + g := tabulate(name, args, reply, req.MaxRows) + columns, rows := g.finish() + r := &model.ExecResult{ + Columns: columns, + Rows: rows, + Truncated: g.truncated, + ElapsedMs: uint64(elapsed.Milliseconds()), + Notices: g.notices, + InTransaction: s.TxState().InTransaction, + } + r.Normalize() + return r, nil +} + +// commandName is the command, uppercased (ASCII only). +func commandName(arg []byte) string { + b := []byte(lossy(arg)) + for i, c := range b { + b[i] = upperASCII(c) + } + return string(b) +} + +// track updates the MULTI state and the selected database after a command. +func (s *Session) track(name string, args [][]byte, reply value, err error) { + s.stateMu.Lock() + defer s.stateMu.Unlock() + trackState(&s.state, name, args, reply, err) +} + +func trackState(st *state, name string, args [][]byte, reply value, err error) { + if err != nil { + // The connection is gone, and the transaction with it. + st.inMulti = false + st.queuedSelect = nil + return + } + failed := reply.typ == vError + switch name { + case "EXEC": + // EXEC and DISCARD end the transaction even when they fail + // (EXECABORT, or no MULTI at all). + if st.queuedSelect != nil && reply.typ == vArray { + st.db = *st.queuedSelect + } + st.queuedSelect = nil + st.inMulti = false + case "DISCARD": + st.inMulti = false + st.queuedSelect = nil + case "MULTI": + if !failed { + st.inMulti = true + } + case "RESET": + if !failed { + *st = state{} + } + case "SELECT": + if failed || len(args) < 2 { + return + } + db, perr := strconv.ParseInt(string(args[1]), 10, 64) + if perr != nil { + return + } + if st.inMulti { + st.queuedSelect = &db + } else { + st.db = db + } + } +} + +func (s *Session) Cancel(ctx context.Context) error { + if !s.busy.Load() { + return nil + } + return s.unblock(ctx) +} + +// unblock sends CLIENT UNBLOCK for this session's connection over a +// short-lived second connection. +func (s *Session) unblock(ctx context.Context) error { + if s.clientID == nil { + return apperr.New(apperr.Invalid, notBlocking) + } + client := goredis.NewClient(s.target.options(s.tls, connectTimeout)) + defer client.Close() + conn := client.EphemeralConn() + defer conn.Close() + ctx, cancel := context.WithTimeout(ctx, connectTimeout) + defer cancel() + v, err := rawCall(ctx, conn, "CLIENT", "UNBLOCK", strconv.FormatInt(*s.clientID, 10), "ERROR") + if err != nil { + return connectError(err) + } + if v.typ == vError { + return serverError(v) + } + if v.typ == vInt && v.i == 0 { + return apperr.New(apperr.Invalid, notBlocking) + } + return nil +} + +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + if on { + return s.TxState(), nil + } + return s.TxState(), apperr.New(apperr.Invalid, "Redis has no autocommit mode; use MULTI and EXEC.") +} + +func (s *Session) EndTransaction(ctx context.Context, commit bool) (model.TxState, error) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.TxState().InTransaction { + return s.TxState(), nil + } + name := "DISCARD" + if commit { + name = "EXEC" + } + reply, err := rawCall(detached(ctx), s.conn, name) + s.track(name, nil, reply, err) + if err != nil { + return s.TxState(), mapError(err) + } + if reply.typ == vError { + return s.TxState(), serverError(reply) + } + return s.TxState(), nil +} + +func (s *Session) checkNotInMulti() error { + if s.TxState().InTransaction { + return apperr.New(apperr.Invalid, "Finish the transaction with EXEC or DISCARD first.") + } + return nil +} + +// ListSchemas returns the current database first, then those with keys, +// then the empty ones (when CONFIG GET databases is allowed). +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + s.mu.Lock() + defer s.mu.Unlock() + if err := s.checkNotInMulti(); err != nil { + return nil, err + } + ctx = detached(ctx) + // A user without INFO or CONFIG rights still sees its database. + keyspace := "" + v, err := s.call(ctx, "INFO", "keyspace") + if err != nil { + if apperr.From(err).Kind == apperr.Connection { + return nil, err + } + } else { + keyspace, _ = textOf(v) + } + var used []int64 + for _, r := range infoRows(keyspace) { + if n, ok := strings.CutPrefix(r[1], "db"); ok { + if db, err := strconv.ParseInt(n, 10, 64); err == nil { + used = append(used, db) + } + } + } + count := int64(0) + if v, err := s.call(ctx, "CONFIG", "GET", "databases"); err == nil { + if text, ok := configValue(v); ok { + if n, err := strconv.ParseInt(text, 10, 64); err == nil { + count = n + } + } + } + + current := s.db() + slices.Sort(used) + dbs := []int64{current} + for _, n := range used { + if n != current { + dbs = append(dbs, n) + } + } + for n := int64(0); n < count; n++ { + if n != current && !slices.Contains(used, n) { + dbs = append(dbs, n) + } + } + out := make([]string, len(dbs)) + for i, n := range dbs { + out[i] = "db" + strconv.FormatInt(n, 10) + } + return out, nil +} + +// ListObjects returns up to MaxKeys keys of the database with their types, +// sorted by type then name. +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + db, ok := parseDB(schema) + if !ok { + return nil, apperr.Invalidf("Unknown database: %s", schema) + } + s.mu.Lock() + defer s.mu.Unlock() + if err := s.checkNotInMulti(); err != nil { + return nil, err + } + ctx = detached(ctx) + current := s.db() + if db != current { + if _, err := s.call(ctx, "SELECT", strconv.FormatInt(db, 10)); err != nil { + return nil, err + } + } + keys, err := s.keyTypes(ctx) + if db != current { + if _, back := s.call(ctx, "SELECT", strconv.FormatInt(current, 10)); back != nil { + s.stateMu.Lock() + s.state.db = db + s.stateMu.Unlock() + } + } + if err != nil { + return nil, err + } + objects := []model.DbObject{} + for _, k := range keys { + if k.kind != "" { + objects = append(objects, model.DbObject{Name: text(k.key), Kind: k.kind}) + } + } + slices.SortFunc(objects, func(a, b model.DbObject) int { + if c := strings.Compare(a.Kind, b.Kind); c != 0 { + return c + } + return strings.Compare(a.Name, b.Name) + }) + return objects, nil +} + +func (s *Session) ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + return []model.DbColumn{}, nil +} + +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + return "", apperr.New(apperr.Invalid, "Redis keys have no DDL.") +} + +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + return nil, apperr.New(apperr.Invalid, "Redis replies cannot be edited in the grid.") +} + +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + return 0, apperr.New(apperr.Invalid, "Redis keys cannot be exported yet.") +} + +type keyType struct { + key []byte + kind string +} + +// keyTypes runs SCAN until MaxKeys keys or the end, then TYPE for each key +// in one pipeline. Keys removed meanwhile have no type. +func (s *Session) keyTypes(ctx context.Context) ([]keyType, error) { + cursor := []byte("0") + var keys [][]byte + for { + v, err := s.call(ctx, "SCAN", cursor, "COUNT", strconv.Itoa(scanCount)) + if err != nil { + return nil, err + } + if v.typ != vArray || len(v.items) != 2 { + return nil, apperr.Internalf("Unexpected SCAN reply.") + } + if found := v.items[1]; found.typ == vArray { + for _, k := range found.items { + if b, ok := bytesOf(k); ok { + keys = append(keys, b) + } + } + } + cursor, _ = bytesOf(v.items[0]) + if string(cursor) == "0" || len(cursor) == 0 || len(keys) >= MaxKeys { + break + } + } + slices.SortFunc(keys, bytes.Compare) + keys = slices.CompactFunc(keys, bytes.Equal) + if len(keys) > MaxKeys { + keys = keys[:MaxKeys] + } + if len(keys) == 0 { + return nil, nil + } + + cmds := make([]*goredis.RawCmd, len(keys)) + _, err := s.conn.Pipelined(ctx, func(p goredis.Pipeliner) error { + for i, k := range keys { + cmds[i] = goredis.NewRawCmd(ctx, "TYPE", k) + if err := p.Process(ctx, cmds[i]); err != nil { + return err + } + } + return nil + }) + if err != nil && !isServerReply(err) { + return nil, mapError(err) + } + out := make([]keyType, len(keys)) + for i, k := range keys { + out[i] = keyType{key: k} + raw, err := cmds[i].Result() + if err != nil { + continue + } + if v, err := parseReply(raw); err == nil { + if t, ok := textOf(v); ok { + out[i].kind = keyKind(t) + } + } + } + return out, nil +} + +// keyKind is the tree kind of a TYPE reply: core types as they are, module +// types lowercased (ReJSON-RL is json). Empty for none. +func keyKind(typeName string) string { + lower := strings.ToLower(strings.TrimSpace(typeName)) + switch lower { + case "", "none": + return "" + case "rejson-rl": + return "json" + } + return lower +} + +// Close closes the connection; a running call is interrupted. +func (s *Session) Close() error { + if !s.mu.TryLock() { + // Closing the client closes its connections, including one in use. + _ = s.client.Close() + s.mu.Lock() + } + defer s.mu.Unlock() + return s.close() +} + +func (s *Session) close() error { + _ = s.conn.Close() + err := s.client.Close() + if errors.Is(err, goredis.ErrClosed) { + return nil + } + return err +} + +// Errors + +// replyError maps an error reply: code is its first word (ERR, WRONGTYPE, +// NOAUTH...), detail the rest. +func replyError(code, detail string) *apperr.Error { + detail = strings.TrimSpace(detail) + kind := apperr.Database + message := detail + switch { + case code == "MOVED" || code == "ASK": + message = "The key is served by another node (" + detail + "). Redis Cluster is not supported yet." + case code == "UNBLOCKED": + // A blocking command interrupted by Cancel. + kind = apperr.Cancelled + message = "The command was interrupted." + case detail == "": + message = code + } + return &apperr.Error{Kind: kind, Message: message, Code: code} +} + +func serverError(v value) *apperr.Error { return replyError(v.code, v.detail) } + +// mapError maps go-redis errors: error replies keep their code, transport +// failures are connection errors. +func mapError(err error) *apperr.Error { + var ae *apperr.Error + if errors.As(err, &ae) { + return ae + } + var re goredis.Error + if errors.As(err, &re) { + code, detail, _ := strings.Cut(re.Error(), " ") + return replyError(code, detail) + } + if errors.Is(err, goredis.ErrClosed) { + return apperr.New(apperr.Connection, closedMessage) + } + return apperr.New(apperr.Connection, err.Error()) +} + +// isServerReply reports whether the server answered (an auth failure, for +// example): the connection itself worked. +func isServerReply(err error) bool { + var re goredis.Error + return errors.As(err, &re) +} + +func isAuthCode(e *apperr.Error) bool { return e.Code == "NOAUTH" || e.Code == "WRONGPASS" } + +// asConnection makes an error from opening a session a connection error; +// NOAUTH and WRONGPASS keep their code. +func asConnection(err error) *apperr.Error { + e := *apperr.From(err) + e.Kind = apperr.Connection + return &e +} + +func connectError(err error) *apperr.Error { + var ne net.Error + if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ne) && ne.Timeout()) { + return apperr.New(apperr.Connection, "Timed out connecting to the server.") + } + e := asConnection(mapError(err)) + // AUTH on a RESP2 server (Redis < 6) answers ERR, not WRONGPASS. + var af authFailed + if errors.As(err, &af) && !isAuthCode(e) { + return &apperr.Error{Kind: apperr.Connection, Message: "Invalid username or password.", Code: "WRONGPASS"} + } + return e +} + +// authFailed is an error reply to the handshake. +type authFailed struct{ err error } + +func (a authFailed) Error() string { return a.err.Error() } +func (a authFailed) Unwrap() error { return a.err } diff --git a/internal/drivers/redis/redis_test.go b/internal/drivers/redis/redis_test.go new file mode 100644 index 0000000..ec9531a --- /dev/null +++ b/internal/drivers/redis/redis_test.go @@ -0,0 +1,356 @@ +package redis + +import ( + "reflect" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func args(t *testing.T, line string) []string { + t.Helper() + raw, err := splitArgs(line) + if err != nil { + t.Fatalf("%s: %v", line, err) + } + out := make([]string, len(raw)) + for i, a := range raw { + out[i] = string(a) + } + return out +} + +func eq(t *testing.T, got, want any) { + t.Helper() + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func splitErr(t *testing.T, line string) *apperr.Error { + t.Helper() + _, err := splitArgs(line) + if err == nil { + t.Fatalf("%s: no error", line) + } + return apperr.From(err) +} + +func TestSplitsLikeRedisCli(t *testing.T) { + eq(t, args(t, " HGETALL user:1 "), []string{"HGETALL", "user:1"}) + eq(t, args(t, `SET k "a b\n"`), []string{"SET", "k", "a b\n"}) + eq(t, args(t, `SET "q\"x\\" 'it\'s' "\t\r\a\b"`), + []string{"SET", "q\"x\\", "it's", "\t\r\x07\x08"}) + // Single quotes keep backslashes except before a quote. + eq(t, args(t, `ECHO 'a\nb'`), []string{"ECHO", `a\nb`}) + // Quotes inside a bare word join it. + eq(t, args(t, `ECHO ab"c d"`), []string{"ECHO", "abc d"}) + eq(t, args(t, `ECHO ""`), []string{"ECHO", ""}) + eq(t, args(t, "ECHO ação"), []string{"ECHO", "ação"}) + eq(t, args(t, " \n "), []string{}) + + raw, err := splitArgs(`SET k "\xff\x41\xZZ"`) + if err != nil { + t.Fatal(err) + } + eq(t, raw[2], []byte("\xffAxZZ")) + + e := splitErr(t, `GET "abc`) + eq(t, e.Kind, apperr.Invalid) + eq(t, *e.Position, 4) + eq(t, splitErr(t, "GET 'abc").Kind, apperr.Invalid) + eq(t, splitErr(t, `GET "a\`).Kind, apperr.Invalid) + e = splitErr(t, `GET "a"b`) + eq(t, e.Kind, apperr.Invalid) + eq(t, *e.Position, 6) + // Positions count characters, not bytes. + e = splitErr(t, `ECHO ação "x`) + eq(t, *e.Position, 10) +} + +func resp(t *testing.T, raw string) value { + t.Helper() + v, err := parseReply([]byte(raw)) + if err != nil { + t.Fatalf("%q: %v", raw, err) + } + return v +} + +type table struct { + cols []model.ColumnInfo + rows []model.Row + grid *grid +} + +func tab(t *testing.T, name, line string, v value, maxRows int) table { + t.Helper() + a, err := splitArgs(line) + if err != nil { + t.Fatal(err) + } + g := tabulate(name, a, v, maxRows) + c, r := g.finish() + return table{c, r, g} +} + +func (tb table) names() []string { + out := make([]string, len(tb.cols)) + for i, c := range tb.cols { + out[i] = c.Name + } + return out +} + +// row shows a row with NULL as "". +func (tb table) row(i int) []string { + out := make([]string, len(tb.rows[i])) + for j, v := range tb.rows[i] { + if v == nil { + out[j] = "" + } else { + out[j] = *v + } + } + return out +} + +func TestFormatsScalars(t *testing.T) { + tb := tab(t, "GET", "GET k", bulk("a b\n"), 0) + eq(t, tb.names(), []string{"value"}) + eq(t, tb.cols[0].Kind, model.KindText) + eq(t, tb.row(0), []string{"a b\n"}) + + tb = tab(t, "INCR", "INCR k", integer(42), 0) + eq(t, tb.cols[0].Kind, model.KindNumber) + eq(t, tb.cols[0].TypeName, "integer") + eq(t, tb.row(0), []string{"42"}) + + tb = tab(t, "ZSCORE", "ZSCORE z m", resp(t, ",1.5\r\n"), 0) + eq(t, tb.cols[0].Kind, model.KindNumber) + eq(t, tb.row(0), []string{"1.5"}) + eq(t, doubleText(3.0), "3") + eq(t, doubleText(resp(t, ",inf\r\n").f), "inf") + eq(t, doubleText(1e300), "1e300") + eq(t, doubleText(1.5e-30), "1.5e-30") + eq(t, doubleText(0.1), "0.1") + + tb = tab(t, "X", "X", resp(t, "#t\r\n"), 0) + eq(t, tb.cols[0].Kind, model.KindBool) + eq(t, tb.row(0), []string{"true"}) + + tb = tab(t, "GET", "GET k", resp(t, "$-1\r\n"), 0) + eq(t, tb.row(0), []string{""}) + tb = tab(t, "GET", "GET k", resp(t, "_\r\n"), 0) + eq(t, tb.row(0), []string{""}) + tb = tab(t, "SET", "SET k v", resp(t, "+OK\r\n"), 0) + eq(t, tb.row(0), []string{"OK"}) + tb = tab(t, "X", "X", resp(t, "(3492890328409238509324850943850943825024385\r\n"), 0) + eq(t, tb.row(0), []string{"3492890328409238509324850943850943825024385"}) + tb = tab(t, "X", "X", resp(t, "=15\r\ntxt:Some string\r\n"), 0) + eq(t, tb.row(0), []string{"Some string"}) + // An attribute is dropped, the reply it describes kept. + tb = tab(t, "GET", "GET k", resp(t, "|1\r\n+ttl\r\n:3600\r\n$1\r\nv\r\n"), 0) + eq(t, tb.row(0), []string{"v"}) +} + +func TestEscapesBinaryStrings(t *testing.T) { + eq(t, text([]byte("\xff\x00a\"\\")), `"\xff\x00a\"\\"`) + eq(t, text([]byte("ação\n")), "ação\n") + eq(t, text([]byte("a\x00b")), `"a\x00b"`) + eq(t, repr([]byte("\x07\x08\t\r\n ")), `"\a\b\t\r\n "`) + tb := tab(t, "GET", "GET k", value{typ: vBulk, s: []byte{0xff, 'a'}}, 0) + eq(t, tb.row(0), []string{`"\xffa"`}) +} + +func TestFormatsMapsAndArrays(t *testing.T) { + // RESP3 HGETALL. + m := resp(t, "%2\r\n$2\r\nf1\r\n$2\r\nv1\r\n$2\r\nf2\r\n:7\r\n") + tb := tab(t, "HGETALL", "HGETALL h", m, 0) + eq(t, tb.names(), []string{"field", "value"}) + eq(t, tb.cols[1].TypeName, "mixed") + eq(t, tb.row(1), []string{"f2", "7"}) + tb = tab(t, "HGETALL", "HGETALL h", m, 1) + eq(t, len(tb.rows), 1) + eq(t, tb.grid.truncated, true) + + // RESP2 HGETALL: a flat list. + flat := resp(t, "*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n") + tb = tab(t, "HGETALL", "HGETALL h", flat, 0) + eq(t, tb.names(), []string{"field", "value"}) + eq(t, tb.row(0), []string{"a", "1"}) + // Other commands: index and value. + tb = tab(t, "LRANGE", "LRANGE l 0 -1", flat, 3) + eq(t, tb.names(), []string{"#", "value"}) + eq(t, tb.cols[0].Kind, model.KindNumber) + eq(t, tb.row(2), []string{"3", "b"}) + eq(t, tb.grid.truncated, true) + + // RESP3 ZRANGE WITHSCORES: [member, score] pairs. + z := resp(t, "*2\r\n*2\r\n$1\r\na\r\n,1\r\n*2\r\n$1\r\nb\r\n,2.5\r\n") + tb = tab(t, "ZRANGE", "ZRANGE z 0 -1 WITHSCORES", z, 0) + eq(t, tb.names(), []string{"member", "score"}) + eq(t, tb.cols[1].Kind, model.KindNumber) + eq(t, tb.row(1), []string{"b", "2.5"}) + tb = tab(t, "LMPOP", "X", z, 0) + eq(t, tb.names(), []string{"1", "2"}) + // RESP2 ZRANGE WITHSCORES: flat, scores as strings. + flat = resp(t, "*2\r\n$1\r\na\r\n$1\r\n1\r\n") + tb = tab(t, "ZRANGE", "ZRANGE z 0 -1 withscores", flat, 0) + eq(t, tb.names(), []string{"member", "score"}) + eq(t, tb.cols[1].Kind, model.KindNumber) + eq(t, tb.row(0), []string{"a", "1"}) + + // Nested values: compact JSON-like text. + nested := resp(t, "*2\r\n*2\r\n$3\r\n1-0\r\n*2\r\n$1\r\nf\r\n$3\r\na\"b\r\n$1\r\nx\r\n") + tb = tab(t, "XRANGE", "XRANGE s - +", nested, 0) + eq(t, tb.names(), []string{"#", "value"}) + eq(t, tb.cols[1].Kind, model.KindText) + eq(t, tb.row(0), []string{"1", `["1-0",["f","a\"b"]]`}) + deep := resp(t, "*1\r\n%1\r\n$1\r\nk\r\n~2\r\n_\r\n$1\r\n\xff\r\n") + tb = tab(t, "X", "X", deep, 0) + eq(t, tb.cols[1].Kind, model.KindJSON) + eq(t, tb.row(0)[1], `{"k":[null,"\xff"]}`) + // Map keys that are not strings become JSON strings; doubles that are + // not finite are quoted. + odd := resp(t, "*1\r\n%2\r\n:1\r\n,inf\r\n$1\r\n\x01\r\n#f\r\n") + tb = tab(t, "X", "X", odd, 0) + eq(t, tb.row(0)[1], `{"1":"inf","\u0001":false}`) + + // EXEC with an error inside. + exec := resp(t, "*2\r\n+OK\r\n-WRONGTYPE Operation against a key\r\n") + tb = tab(t, "EXEC", "EXEC", exec, 0) + eq(t, tb.row(1), []string{"2", "(error) WRONGTYPE Operation against a key"}) + + // Empty list. + tb = tab(t, "KEYS", "KEYS x*", array([]value{}), 0) + eq(t, tb.names(), []string{"#", "value"}) + eq(t, len(tb.rows), 0) + + // Map order is the server's. + ordered := resp(t, "%3\r\n$1\r\nz\r\n:1\r\n$1\r\na\r\n:2\r\n$1\r\nm\r\n:3\r\n") + tb = tab(t, "HGETALL", "HGETALL h", ordered, 0) + eq(t, []string{tb.row(0)[0], tb.row(1)[0], tb.row(2)[0]}, []string{"z", "a", "m"}) +} + +func TestScanRepliesShowTheCursor(t *testing.T) { + v := resp(t, "*2\r\n$2\r\n17\r\n*4\r\n$1\r\nf\r\n$1\r\nv\r\n$1\r\ng\r\n$1\r\nw\r\n") + tb := tab(t, "HSCAN", "HSCAN h 0", v, 0) + eq(t, tb.names(), []string{"field", "value"}) + eq(t, len(tb.rows), 2) + eq(t, tb.grid.notices, []string{"Next cursor: 17"}) + tb = tab(t, "SSCAN", "SSCAN s 0", v, 0) + eq(t, tb.names(), []string{"#", "value"}) + eq(t, len(tb.rows), 4) + done := resp(t, "*2\r\n$1\r\n0\r\n*0\r\n") + tb = tab(t, "SCAN", "SCAN 0", done, 0) + eq(t, tb.grid.notices, []string{"Next cursor: 0 (the scan is complete)."}) +} + +func TestParsesInfo(t *testing.T) { + info := "# Server\r\nredis_version:7.4.1\r\nredis_mode:standalone\r\n\r\n# Keyspace\r\ndb0:keys=3,expires=0,avg_ttl=0\r\n" + tb := tab(t, "INFO", "INFO", bulk(info), 0) + eq(t, tb.names(), []string{"section", "key", "value"}) + eq(t, len(tb.rows), 3) + eq(t, tb.row(0), []string{"Server", "redis_version", "7.4.1"}) + eq(t, tb.row(2), []string{"Keyspace", "db0", "keys=3,expires=0,avg_ttl=0"}) + tb = tab(t, "INFO", "INFO", bulk(info), 2) + eq(t, len(tb.rows), 2) + eq(t, tb.grid.truncated, true) + // RESP3 sends INFO as a verbatim string. + tb = tab(t, "INFO", "INFO", resp(t, "=19\r\ntxt:# A\r\nk:v\r\nx:1:2\r\n"), 0) + eq(t, tb.row(1), []string{"A", "x", "1:2"}) + + eq(t, productVersion(info), "Redis 7.4.1") + eq(t, productVersion("redis_version:7.2.4\r\nserver_name:valkey\r\nvalkey_version:8.1.0\r\n"), "Valkey 8.1.0") + eq(t, productVersion("dragonfly_version:df-v1.27.1\r\n"), "Dragonfly 1.27.1") + eq(t, productVersion(""), "Redis") +} + +func TestMapsErrorsAndKinds(t *testing.T) { + err := serverError(resp(t, "-WRONGTYPE Operation against a key\r\n")) + eq(t, err.Kind, apperr.Database) + eq(t, err.Code, "WRONGTYPE") + eq(t, err.Message, "Operation against a key") + err = serverError(resp(t, "-MOVED 3999 127.0.0.1:6381\r\n")) + eq(t, err.Code, "MOVED") + eq(t, err.Message, "The key is served by another node (3999 127.0.0.1:6381). Redis Cluster is not supported yet.") + err = serverError(resp(t, "-UNBLOCKED client unblocked via CLIENT UNBLOCK\r\n")) + eq(t, err.Kind, apperr.Cancelled) + err = serverError(resp(t, "-ERR\r\n")) + eq(t, err.Message, "ERR") + err = serverError(resp(t, "!21\r\nSYNTAX invalid syntax\r\n")) + eq(t, err.Code, "SYNTAX") + eq(t, err.Message, "invalid syntax") + + eq(t, keyKind("ReJSON-RL"), "json") + eq(t, keyKind("zset"), "zset") + eq(t, keyKind("TSDB-TYPE"), "tsdb-type") + eq(t, keyKind("none"), "") + + db := func(s string) any { + n, ok := parseDB(s) + if !ok { + return nil + } + return n + } + eq(t, db(""), int64(0)) + eq(t, db(" 3 "), int64(3)) + eq(t, db("db12"), int64(12)) + eq(t, db("DB2"), int64(2)) + eq(t, db("x"), nil) + eq(t, db("-1"), nil) +} + +func TestTracksMulti(t *testing.T) { + var st state + a := func(l string) [][]byte { + v, err := splitArgs(l) + if err != nil { + t.Fatal(err) + } + return v + } + ok := resp(t, "+OK\r\n") + trackState(&st, "MULTI", a("MULTI"), ok, nil) + eq(t, st.inMulti, true) + trackState(&st, "SELECT", a("SELECT 4"), simple("QUEUED"), nil) + eq(t, st.db, int64(0)) + eq(t, *st.queuedSelect, int64(4)) + errReply := resp(t, "-ERR unknown command\r\n") + trackState(&st, "NOPE", a("NOPE"), errReply, nil) + eq(t, st.inMulti, true) + trackState(&st, "EXEC", a("EXEC"), array([]value{ok}), nil) + eq(t, st.inMulti, false) + eq(t, st.db, int64(4)) + trackState(&st, "MULTI", a("MULTI"), ok, nil) + trackState(&st, "EXEC", a("EXEC"), resp(t, "-EXECABORT Transaction discarded\r\n"), nil) + eq(t, st.inMulti, false) + trackState(&st, "SELECT", a("SELECT 2"), ok, nil) + eq(t, st.db, int64(2)) + trackState(&st, "SELECT", a("SELECT 99"), errReply, nil) + eq(t, st.db, int64(2)) + // A lost connection ends the transaction. + trackState(&st, "MULTI", a("MULTI"), ok, nil) + trackState(&st, "GET", a("GET k"), value{}, apperr.New(apperr.Connection, "gone")) + eq(t, st.inMulti, false) + trackState(&st, "RESET", a("RESET"), simple("RESET"), nil) + eq(t, st.db, int64(0)) +} + +func TestParsesReplies(t *testing.T) { + for _, bad := range []string{"", "$5\r\nab\r\n", "*2\r\n:1\r\n", "?x\r\n", ":x\r\n"} { + if _, err := parseReply([]byte(bad)); err == nil { + t.Errorf("%q: no error", bad) + } + } + v := resp(t, "*-1\r\n") + eq(t, v.typ, vNil) + v = resp(t, ">2\r\n+message\r\n:1\r\n") + eq(t, v.typ, vPush) + eq(t, typeName(v), "array") + v = resp(t, "$4\r\na\r\nb\r\n") + eq(t, v.s, []byte("a\r\nb")) +} diff --git a/internal/drivers/redis/reply.go b/internal/drivers/redis/reply.go new file mode 100644 index 0000000..6b24073 --- /dev/null +++ b/internal/drivers/redis/reply.go @@ -0,0 +1,232 @@ +package redis + +import ( + "bytes" + "errors" + "strconv" + "strings" +) + +// valueType is the RESP type of a reply value. RESP2 replies map onto the +// same types (status lines are simple strings, null bulk strings and null +// arrays are nil). +type valueType uint8 + +const ( + vNil valueType = iota + vInt + vDouble + vBool + vBigNumber + vBulk + vSimple + vVerbatim + vArray + vSet + vMap + vPush + vAttribute + vError +) + +// value is one reply, parsed from the raw RESP bytes so that map order, +// sets, doubles and binary strings survive as they are. +type value struct { + typ valueType + i int64 + f float64 + b bool + // Bulk, simple and verbatim strings (verbatim without its format + // prefix), big numbers. + s []byte + // Array, set and push items; map entries as key, value, key, value...; + // the reply an attribute is attached to, as its only item. + items []value + // Error replies: the first word (ERR, WRONGTYPE...) and the rest. + code string + detail string + hasDetail bool +} + +func bulk(s string) value { return value{typ: vBulk, s: []byte(s)} } +func simple(s string) value { return value{typ: vSimple, s: []byte(s)} } +func integer(i int64) value { return value{typ: vInt, i: i} } +func array(items []value) value { return value{typ: vArray, items: items} } + +// pairs returns the entries of a map. +func (v value) pairs() [][2]value { + out := make([][2]value, 0, len(v.items)/2) + for i := 0; i+1 < len(v.items); i += 2 { + out = append(out, [2]value{v.items[i], v.items[i+1]}) + } + return out +} + +// errorValue splits an error line the way redis-rs does: the code is the +// first word, the detail the rest. +func errorValue(line []byte) value { + code, detail, found := strings.Cut(string(line), " ") + return value{typ: vError, code: code, detail: detail, hasDetail: found} +} + +var errIncomplete = errors.New("incomplete reply") + +// parseReply parses one complete RESP2/RESP3 reply. +func parseReply(raw []byte) (value, error) { + p := parser{buf: raw} + v, err := p.value(0) + if err != nil { + return value{}, err + } + return v, nil +} + +type parser struct { + buf []byte + pos int +} + +// maxDepth bounds nesting, as a guard against malformed input. +const maxDepth = 512 + +func (p *parser) line() ([]byte, error) { + i := bytes.Index(p.buf[p.pos:], []byte("\r\n")) + if i < 0 { + return nil, errIncomplete + } + line := p.buf[p.pos : p.pos+i] + p.pos += i + 2 + return line, nil +} + +func (p *parser) length(text []byte) (int, error) { + n, err := strconv.Atoi(string(text)) + if err != nil { + return 0, errors.New("invalid length in reply") + } + return n, nil +} + +// blob reads n bytes and the CRLF after them. +func (p *parser) blob(n int) ([]byte, error) { + if n < 0 || p.pos+n+2 > len(p.buf) { + return nil, errIncomplete + } + out := p.buf[p.pos : p.pos+n] + p.pos += n + 2 + return out, nil +} + +func (p *parser) values(n, depth int) ([]value, error) { + items := make([]value, 0, min(n, 1024)) + for range n { + v, err := p.value(depth + 1) + if err != nil { + return nil, err + } + items = append(items, v) + } + return items, nil +} + +func (p *parser) value(depth int) (value, error) { + if depth > maxDepth { + return value{}, errors.New("reply nested too deeply") + } + line, err := p.line() + if err != nil { + return value{}, err + } + if len(line) == 0 { + return value{}, errors.New("empty reply line") + } + head, rest := line[0], line[1:] + switch head { + case '+': + return value{typ: vSimple, s: rest}, nil + case '-': + return errorValue(rest), nil + case ':': + n, err := strconv.ParseInt(string(rest), 10, 64) + if err != nil { + return value{}, errors.New("invalid integer in reply") + } + return integer(n), nil + case '_': + return value{typ: vNil}, nil + case ',': + f, err := strconv.ParseFloat(string(rest), 64) + if err != nil { + return value{}, errors.New("invalid double in reply") + } + return value{typ: vDouble, f: f}, nil + case '#': + return value{typ: vBool, b: len(rest) > 0 && rest[0] == 't'}, nil + case '(': + return value{typ: vBigNumber, s: rest}, nil + case '$', '=', '!': + n, err := p.length(rest) + if err != nil { + return value{}, err + } + if n < 0 { + return value{typ: vNil}, nil + } + data, err := p.blob(n) + if err != nil { + return value{}, err + } + switch head { + case '=': + // "txt:" or "mkd:" first. + if len(data) >= 4 && data[3] == ':' { + data = data[4:] + } + return value{typ: vVerbatim, s: data}, nil + case '!': + return errorValue(data), nil + } + return value{typ: vBulk, s: data}, nil + case '*', '~', '>': + n, err := p.length(rest) + if err != nil { + return value{}, err + } + if n < 0 { + return value{typ: vNil}, nil + } + items, err := p.values(n, depth) + if err != nil { + return value{}, err + } + typ := vArray + if head == '~' { + typ = vSet + } else if head == '>' { + typ = vPush + } + return value{typ: typ, items: items}, nil + case '%', '|': + n, err := p.length(rest) + if err != nil { + return value{}, err + } + if n < 0 { + return value{typ: vNil}, nil + } + entries, err := p.values(2*n, depth) + if err != nil { + return value{}, err + } + if head == '%' { + return value{typ: vMap, items: entries}, nil + } + // An attribute comes before the reply it describes. + data, err := p.value(depth + 1) + if err != nil { + return value{}, err + } + return value{typ: vAttribute, items: []value{data}}, nil + } + return value{}, errors.New("unknown reply type " + strconv.QuoteRune(rune(head))) +} diff --git a/internal/drivers/redis/table.go b/internal/drivers/redis/table.go new file mode 100644 index 0000000..ac8b2ff --- /dev/null +++ b/internal/drivers/redis/table.go @@ -0,0 +1,557 @@ +package redis + +import ( + "fmt" + "math" + "slices" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// Replies as tables. + +// grid holds rows of reply values before formatting. +type grid struct { + names []string + rows [][]value + truncated bool + notices []string +} + +func newGrid(names ...string) *grid { + return &grid{names: names} +} + +func (g *grid) finish() ([]model.ColumnInfo, []model.Row) { + columns := make([]model.ColumnInfo, len(g.names)) + for i, name := range g.names { + var values []value + for _, r := range g.rows { + if i < len(r) && r[i].typ != vNil { + values = append(values, r[i]) + } + } + kind := columnKind(values) + if name == "#" || name == "score" { + kind = model.KindNumber + } + columns[i] = model.ColumnInfo{Name: name, TypeName: columnType(values), Kind: kind} + } + rows := make([]model.Row, len(g.rows)) + for i, r := range g.rows { + row := make(model.Row, len(r)) + for j, v := range r { + row[j] = cell(v) + } + rows[i] = row + } + return columns, rows +} + +// limit keeps at most maxRows items (0 = all); true when some were dropped. +func limit[T any](items []T, maxRows int) ([]T, bool) { + if maxRows > 0 && len(items) > maxRows { + return items[:maxRows], true + } + return items, false +} + +func isAggregate(v value) bool { + switch v.typ { + case vArray, vSet, vMap, vPush, vAttribute: + return true + } + return false +} + +func unwrapAttribute(v value) value { + for v.typ == vAttribute && len(v.items) == 1 { + v = v.items[0] + } + return v +} + +// hasScores: sorted-set replies whose pairs are member and score. +func hasScores(name string, args [][]byte) bool { + return strings.HasPrefix(name, "Z") && + (hasArg(args, "WITHSCORES") || name == "ZPOPMIN" || name == "ZPOPMAX") +} + +// hasFieldPairs: commands whose RESP2 reply is a flat field/value list. +func hasFieldPairs(name string, args [][]byte) bool { + switch name { + case "HGETALL": + return true + case "CONFIG": + return argIs(args, 1, "GET") + case "HRANDFIELD": + return hasArg(args, "WITHVALUES") + } + return false +} + +func tabulate(name string, args [][]byte, v value, maxRows int) *grid { + v = unwrapAttribute(v) + if name == "INFO" { + if text, ok := textOf(v); ok { + rows, truncated := limit(infoRows(text), maxRows) + g := newGrid("section", "key", "value") + g.truncated = truncated + for _, r := range rows { + g.rows = append(g.rows, []value{simple(r[0]), simple(r[1]), simple(r[2])}) + } + return g + } + } + switch v.typ { + case vArray, vSet, vPush: + if v.typ == vArray && isScan(name) && len(v.items) == 2 && v.items[1].typ == vArray { + items := v.items[1].items + cursor := "" + if c := cell(v.items[0]); c != nil { + cursor = *c + } + var g *grid + switch { + case name == "HSCAN" && !hasArg(args, "NOVALUES"): + g = pairs(items, "field", "value", maxRows) + case name == "ZSCAN": + g = pairs(items, "member", "score", maxRows) + default: + g = list(items, maxRows) + } + if cursor == "0" { + g.notices = append(g.notices, "Next cursor: 0 (the scan is complete).") + } else { + g.notices = append(g.notices, "Next cursor: "+cursor) + } + return g + } + items := v.items + if width := tupleWidth(items); width > 0 { + var names []string + switch { + case width == 2 && hasScores(name, args): + names = []string{"member", "score"} + case width == 2 && (name == "XRANGE" || name == "XREVRANGE"): + names = []string{"id", "fields"} + default: + for i := 1; i <= width; i++ { + names = append(names, strconv.Itoa(i)) + } + } + g := &grid{names: names} + items, g.truncated = limit(items, maxRows) + for _, t := range items { + g.rows = append(g.rows, t.items) + } + return g + } + flat := len(items)%2 == 0 && !slices.ContainsFunc(items, isAggregate) + switch { + case flat && hasScores(name, args): + return pairs(items, "member", "score", maxRows) + case flat && hasFieldPairs(name, args): + return pairs(items, "field", "value", maxRows) + } + return list(items, maxRows) + case vMap: + g := newGrid("field", "value") + entries, truncated := limit(v.pairs(), maxRows) + g.truncated = truncated + for _, e := range entries { + g.rows = append(g.rows, []value{e[0], e[1]}) + } + return g + } + g := newGrid("value") + g.rows = [][]value{{v}} + return g +} + +func isScan(name string) bool { + switch name { + case "SCAN", "SSCAN", "HSCAN", "ZSCAN": + return true + } + return false +} + +// tupleWidth is the width of a non-empty list whose items are all arrays of +// the same length (at least 2), or 0. +func tupleWidth(items []value) int { + width := 0 + for _, item := range items { + if item.typ != vArray || len(item.items) < 2 || (width != 0 && width != len(item.items)) { + return 0 + } + width = len(item.items) + } + return width +} + +func list(items []value, maxRows int) *grid { + g := newGrid("#", "value") + items, g.truncated = limit(items, maxRows) + for i, v := range items { + g.rows = append(g.rows, []value{integer(int64(i) + 1), v}) + } + return g +} + +// pairs lays out a flat [a1, b1, a2, b2...] list as two columns. +func pairs(items []value, a, b string, maxRows int) *grid { + if len(items)%2 != 0 { + return list(items, maxRows) + } + g := newGrid(a, b) + rows := make([][]value, 0, len(items)/2) + for i := 0; i+1 < len(items); i += 2 { + rows = append(rows, []value{items[i], items[i+1]}) + } + g.rows, g.truncated = limit(rows, maxRows) + return g +} + +// infoRows returns [section, key, value] rows from INFO text (# Section +// and key:value lines). +func infoRows(text string) [][3]string { + section := "" + var rows [][3]string + for _, line := range lines(text) { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if name, ok := strings.CutPrefix(line, "#"); ok { + section = strings.TrimSpace(name) + continue + } + key, val, _ := strings.Cut(line, ":") + rows = append(rows, [3]string{section, key, val}) + } + return rows +} + +// lines splits text on \n, dropping the \r of \r\n endings. +func lines(text string) []string { + out := strings.Split(text, "\n") + if len(out) > 0 && out[len(out)-1] == "" { + out = out[:len(out)-1] + } + for i, l := range out { + out[i] = strings.TrimSuffix(l, "\r") + } + return out +} + +// configValue is the value of CONFIG GET (a map in RESP3, +// a pair in RESP2). +func configValue(v value) (string, bool) { + switch { + case v.typ == vMap && len(v.items) >= 2: + return textOf(v.items[len(v.items)-1]) + case v.typ == vArray && len(v.items) == 2: + return textOf(v.items[1]) + } + return "", false +} + +func typeName(v value) string { + switch v.typ { + case vNil: + return "nil" + case vInt: + return "integer" + case vDouble: + return "double" + case vBool: + return "boolean" + case vBigNumber: + return "big number" + case vBulk, vSimple: + return "string" + case vVerbatim: + return "verbatim string" + case vArray, vPush: + return "array" + case vSet: + return "set" + case vMap, vAttribute: + return "map" + case vError: + return "error" + } + return "other" +} + +func columnType(values []value) string { + if len(values) == 0 { + return "nil" + } + first := typeName(values[0]) + for _, v := range values[1:] { + if typeName(v) != first { + return "mixed" + } + } + return first +} + +func columnKind(values []value) model.ValueKind { + all := func(f func(value) bool) bool { + for _, v := range values { + if !f(v) { + return false + } + } + return true + } + switch { + case len(values) == 0: + return model.KindText + case all(func(v value) bool { return v.typ == vInt || v.typ == vDouble || v.typ == vBigNumber }): + return model.KindNumber + case all(func(v value) bool { return v.typ == vBool }): + return model.KindBool + case all(isAggregate): + return model.KindJSON + } + return model.KindText +} + +// cell is the text of a value: scalars as they are, nested values as +// compact JSON-like text, errors inside a reply (EXEC) as +// "(error) CODE message". Nil is NULL. +func cell(v value) *string { + switch { + case v.typ == vNil: + return nil + case v.typ == vError: + return model.Str(errorText(v)) + case isAggregate(v): + var out strings.Builder + writeNested(&out, v) + return model.Str(out.String()) + } + return model.Str(scalarText(v)) +} + +func scalarText(v value) string { + switch v.typ { + case vInt: + return strconv.FormatInt(v.i, 10) + case vDouble: + return doubleText(v.f) + case vBool: + return strconv.FormatBool(v.b) + case vBigNumber, vSimple, vVerbatim: + return lossy(v.s) + case vBulk: + return text(v.s) + case vNil: + return "" + } + if c := cell(v); c != nil { + return *c + } + return "" +} + +// doubleText formats a double the way Rust prints an f64: shortest form, +// no exponent unless the plain form is longer than 24 characters. +func doubleText(d float64) string { + switch { + case math.IsNaN(d): + return "nan" + case math.IsInf(d, 1): + return "inf" + case math.IsInf(d, -1): + return "-inf" + } + plain := strconv.FormatFloat(d, 'f', -1, 64) + if len(plain) <= 24 { + return plain + } + mantissa, exp, _ := strings.Cut(strconv.FormatFloat(d, 'e', -1, 64), "e") + n, _ := strconv.Atoi(exp) + return mantissa + "e" + strconv.Itoa(n) +} + +func errorText(v value) string { + if v.hasDetail { + return "(error) " + v.code + " " + v.detail + } + return "(error) " + v.code +} + +// text shows bytes as text when they are readable UTF-8, otherwise in +// redis-cli's quoted form with escapes ("\xff"), which never loses data. +func text(b []byte) string { + if utf8.Valid(b) { + readable := true + for _, r := range string(b) { + if unicode.IsControl(r) && r != '\n' && r != '\r' && r != '\t' { + readable = false + break + } + } + if readable { + return string(b) + } + } + return repr(b) +} + +// repr is redis-cli's sdscatrepr. +func repr(b []byte) string { + var out strings.Builder + out.Grow(len(b) + 2) + out.WriteByte('"') + for _, c := range b { + switch { + case c == '\\': + out.WriteString(`\\`) + case c == '"': + out.WriteString(`\"`) + case c == '\n': + out.WriteString(`\n`) + case c == '\r': + out.WriteString(`\r`) + case c == '\t': + out.WriteString(`\t`) + case c == 0x07: + out.WriteString(`\a`) + case c == 0x08: + out.WriteString(`\b`) + case c >= 0x20 && c <= 0x7e: + out.WriteByte(c) + default: + fmt.Fprintf(&out, `\x%02x`, c) + } + } + out.WriteByte('"') + return out.String() +} + +func lossy(b []byte) string { return strings.ToValidUTF8(string(b), "�") } + +// jsonString writes s as a JSON string, escaping like serde_json: quotes, +// backslashes and control characters only. +func jsonString(out *strings.Builder, s string) { + const hex = "0123456789abcdef" + out.WriteByte('"') + for _, r := range s { + switch { + case r == '"': + out.WriteString(`\"`) + case r == '\\': + out.WriteString(`\\`) + case r == '\n': + out.WriteString(`\n`) + case r == '\r': + out.WriteString(`\r`) + case r == '\t': + out.WriteString(`\t`) + case r == 0x08: + out.WriteString(`\b`) + case r == 0x0c: + out.WriteString(`\f`) + case r < 0x20: + out.WriteString(`\u00`) + out.WriteByte(hex[r>>4]) + out.WriteByte(hex[r&0xf]) + default: + out.WriteRune(r) + } + } + out.WriteByte('"') +} + +// writeNested writes compact JSON-like text. Binary strings keep +// redis-cli escapes. +func writeNested(out *strings.Builder, v value) { + switch v.typ { + case vNil: + out.WriteString("null") + case vInt: + out.WriteString(strconv.FormatInt(v.i, 10)) + case vDouble: + if math.IsNaN(v.f) || math.IsInf(v.f, 0) { + jsonString(out, doubleText(v.f)) + } else { + out.WriteString(doubleText(v.f)) + } + case vBool: + out.WriteString(strconv.FormatBool(v.b)) + case vBigNumber: + out.WriteString(lossy(v.s)) + case vBulk: + if utf8.Valid(v.s) { + jsonString(out, string(v.s)) + } else { + out.WriteString(repr(v.s)) + } + case vSimple, vVerbatim: + jsonString(out, lossy(v.s)) + case vArray, vSet, vPush: + out.WriteByte('[') + for i, item := range v.items { + if i > 0 { + out.WriteByte(',') + } + writeNested(out, item) + } + out.WriteByte(']') + case vMap: + out.WriteByte('{') + for i, e := range v.pairs() { + if i > 0 { + out.WriteByte(',') + } + switch e[0].typ { + case vBulk, vSimple, vVerbatim: + writeNested(out, e[0]) + default: + var key strings.Builder + writeNested(&key, e[0]) + jsonString(out, key.String()) + } + out.WriteByte(':') + writeNested(out, e[1]) + } + out.WriteByte('}') + case vAttribute: + if len(v.items) == 1 { + writeNested(out, v.items[0]) + } else { + out.WriteString("null") + } + case vError: + jsonString(out, errorText(v)) + default: + out.WriteString("null") + } +} + +// textOf is the text of a string-like reply. +func textOf(v value) (string, bool) { + switch v.typ { + case vBulk, vSimple, vVerbatim: + return lossy(v.s), true + } + return "", false +} + +// bytesOf is the content of a bulk or simple string. +func bytesOf(v value) ([]byte, bool) { + switch v.typ { + case vBulk, vSimple: + return v.s, true + } + return nil, false +} diff --git a/internal/drivers/sqlite/sqlite_test.go b/internal/drivers/sqlite/sqlite_test.go index d8826dd..5e6a348 100644 --- a/internal/drivers/sqlite/sqlite_test.go +++ b/internal/drivers/sqlite/sqlite_test.go @@ -40,7 +40,7 @@ type tempDB struct { // closed before the directory is removed. func newTempDB(t *testing.T, name string) *tempDB { t.Helper() - dir := t.TempDir() + dir := tempDir(t) s, err := Connect(bg, profile(filepath.Join(dir, name+".db"), true)) if err != nil { t.Fatal(err) @@ -49,6 +49,26 @@ func newTempDB(t *testing.T, name string) *tempDB { return &tempDB{t: t, dir: dir, s: s} } +// tempDir is t.TempDir without failing the test when the folder cannot be +// removed: on Windows an antivirus may still hold a database file that was +// just closed. +func tempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("", "lq-sqlite-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + for range 20 { + if os.RemoveAll(dir) == nil { + return + } + time.Sleep(100 * time.Millisecond) + } + }) + return dir +} + func (db *tempDB) run(sql string) *model.ExecResult { db.t.Helper() return db.runLimit(sql, 0) @@ -514,7 +534,7 @@ func TestContextStopsQuery(t *testing.T) { } func TestCreatesFileOnlyWhenAsked(t *testing.T) { - dir := t.TempDir() + dir := tempDir(t) path := filepath.Join(dir, "create.db") _, err := Connect(bg, profile(path, false)) e := asApp(t, err) diff --git a/internal/drivers/sqlserver/ddl.go b/internal/drivers/sqlserver/ddl.go new file mode 100644 index 0000000..c2603f1 --- /dev/null +++ b/internal/drivers/sqlserver/ddl.go @@ -0,0 +1,315 @@ +package sqlserver + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// ObjectDDL returns the statements that create an object. Views, routines +// and triggers come from OBJECT_DEFINITION; tables, sequences, synonyms and +// alias types are scripted from the catalog. Batches are separated by GO. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + object := objectID(schema, name) + target := quoteIdent(schema) + "." + quoteIdent(name) + switch kind { + case "view", "function", "procedure": + rows, err := s.metadata(ctx, "SELECT OBJECT_DEFINITION("+object+")") + if err != nil { + return "", err + } + def := "" + if len(rows) > 0 { + def = cellText(rows[0], 0) + } + if strings.TrimSpace(def) == "" { + return def, nil + } + return strings.TrimSpace(def) + "\nGO\n", nil + case "table": + return s.tableDDL(ctx, object, target) + case "sequence": + rows, err := s.metadata(ctx, `SELECT TYPE_NAME(s.user_type_id), CAST(s.start_value AS nvarchar(60)), + CAST(s.increment AS nvarchar(60)), CAST(s.minimum_value AS nvarchar(60)), + CAST(s.maximum_value AS nvarchar(60)), s.is_cycling, s.is_cached, + CAST(s.cache_size AS nvarchar(20)) + FROM sys.sequences s WHERE s.object_id = `+object) + if err != nil { + return "", err + } + if len(rows) == 0 { + return "", nil + } + q := rows[0] + cache := "CACHE" + switch size := cellText(q, 7); { + case cellText(q, 6) == "false": + cache = "NO CACHE" + case size != "": + cache = "CACHE " + size + } + cycle := "NO " + if cellText(q, 5) == "true" { + cycle = "" + } + return fmt.Sprintf("CREATE SEQUENCE %s\n AS %s\n START WITH %s\n INCREMENT BY %s\n MINVALUE %s\n MAXVALUE %s\n %sCYCLE\n %s;\n", + target, cellText(q, 0), cellText(q, 1), cellText(q, 2), cellText(q, 3), cellText(q, 4), cycle, cache), nil + case "synonym": + rows, err := s.metadata(ctx, "SELECT base_object_name FROM sys.synonyms WHERE object_id = "+object) + if err != nil { + return "", err + } + base := "" + if len(rows) > 0 { + base = cellText(rows[0], 0) + } + return "CREATE SYNONYM " + target + " FOR " + base + ";\n", nil + case "type": + rows, err := s.metadata(ctx, `SELECT b.name, CAST(t.max_length AS int), CAST(t.precision AS int), + CAST(t.scale AS int), t.is_nullable, t.is_table_type + FROM sys.types t + LEFT JOIN sys.types b ON b.user_type_id = t.system_type_id + WHERE t.schema_id = SCHEMA_ID(`+nstr(schema)+`) AND t.name = `+nstr(name)) + if err != nil { + return "", err + } + if len(rows) == 0 { + return "", nil + } + q := rows[0] + if cellText(q, 5) == "true" { + return "", apperr.Invalidf("LowQuery cannot script table types yet.") + } + num := func(i int) int64 { + n, _ := strconv.ParseInt(cellText(q, i), 10, 64) + return n + } + base := cellText(q, 0) + ty := base + switch base { + case "varchar", "char", "varbinary", "binary": + if num(1) == -1 { + ty = base + "(max)" + } else { + ty = fmt.Sprintf("%s(%d)", base, num(1)) + } + case "nvarchar", "nchar": + if num(1) == -1 { + ty = base + "(max)" + } else { + ty = fmt.Sprintf("%s(%d)", base, num(1)/2) + } + case "decimal", "numeric": + ty = fmt.Sprintf("%s(%d,%d)", base, num(2), num(3)) + case "datetime2", "time", "datetimeoffset": + ty = fmt.Sprintf("%s(%d)", base, num(3)) + } + null := "NOT NULL" + if cellText(q, 4) == "true" { + null = "NULL" + } + return "CREATE TYPE " + target + " FROM " + ty + " " + null + ";\n", nil + } + return "", apperr.Invalidf("LowQuery cannot script a %s on SQL Server.", kind) +} + +func (s *Session) tableDDL(ctx context.Context, object, target string) (string, error) { + columns, err := s.metadata(ctx, `SELECT c.name, `+columnType+`, c.is_nullable, c.is_identity, + CAST(ic.seed_value AS nvarchar(60)), CAST(ic.increment_value AS nvarchar(60)), + cc.definition, cc.is_persisted, dc.name, dc.definition + FROM sys.columns c + JOIN sys.types t ON t.user_type_id = c.user_type_id + LEFT JOIN sys.identity_columns ic + ON ic.object_id = c.object_id AND ic.column_id = c.column_id + LEFT JOIN sys.computed_columns cc + ON cc.object_id = c.object_id AND cc.column_id = c.column_id + LEFT JOIN sys.default_constraints dc + ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id + WHERE c.object_id = `+object+` + ORDER BY c.column_id`) + if err != nil { + return "", err + } + if len(columns) == 0 { + return "", nil + } + lines := make([]string, 0, len(columns)) + for _, c := range columns { + name := quoteIdent(cellText(c, 0)) + if computed := cellText(c, 6); computed != "" { + persisted := "" + if cellText(c, 7) == "true" { + persisted = " PERSISTED" + } + lines = append(lines, " "+name+" AS "+computed+persisted) + continue + } + line := " " + name + " " + cellText(c, 1) + if cellText(c, 3) == "true" { + line += fmt.Sprintf(" IDENTITY(%s,%s)", cellText(c, 4), cellText(c, 5)) + } + if cellText(c, 2) == "true" { + line += " NULL" + } else { + line += " NOT NULL" + } + if def := cellText(c, 9); def != "" { + line += " CONSTRAINT " + quoteIdent(cellText(c, 8)) + " DEFAULT " + def + } + lines = append(lines, line) + } + + // Primary key and unique constraints, one row per key column. + keys, err := s.metadata(ctx, `SELECT kc.name, kc.type, i.type_desc, col.name, ic.is_descending_key + FROM sys.key_constraints kc + JOIN sys.indexes i ON i.object_id = kc.parent_object_id AND i.index_id = kc.unique_index_id + JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id + JOIN sys.columns col ON col.object_id = ic.object_id AND col.column_id = ic.column_id + WHERE kc.parent_object_id = `+object+` + ORDER BY kc.type, kc.name, ic.key_ordinal`) + if err != nil { + return "", err + } + for _, g := range groupByFirst(keys) { + kind := "UNIQUE" + if cellText(g.rows[0], 1) == "PK" { + kind = "PRIMARY KEY" + } + cols := make([]string, len(g.rows)) + for i, r := range g.rows { + cols[i] = quoteIdent(cellText(r, 3)) + desc(cellText(r, 4)) + } + lines = append(lines, fmt.Sprintf(" CONSTRAINT %s %s %s (%s)", + quoteIdent(g.key), kind, cellText(g.rows[0], 2), strings.Join(cols, ", "))) + } + checks, err := s.metadata(ctx, `SELECT name, definition FROM sys.check_constraints + WHERE parent_object_id = `+object+` ORDER BY name`) + if err != nil { + return "", err + } + for _, c := range checks { + lines = append(lines, " CONSTRAINT "+quoteIdent(cellText(c, 0))+" CHECK "+cellText(c, 1)) + } + var out strings.Builder + out.WriteString("CREATE TABLE " + target + " (\n" + strings.Join(lines, ",\n") + "\n);\n") + + indexes, err := s.metadata(ctx, `SELECT i.name, i.is_unique, i.type_desc, c.name, ic.is_descending_key, + ic.is_included_column, i.filter_definition + FROM sys.indexes i + JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id + JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id + WHERE i.object_id = `+object+` AND i.is_primary_key = 0 + AND i.is_unique_constraint = 0 AND i.type IN (1, 2) + ORDER BY i.name, ic.is_included_column, ic.key_ordinal, ic.index_column_id`) + if err != nil { + return "", err + } + for _, g := range groupByFirst(indexes) { + unique := "" + if cellText(g.rows[0], 1) == "true" { + unique = "UNIQUE " + } + var key, include []string + for _, r := range g.rows { + if cellText(r, 5) == "true" { + include = append(include, quoteIdent(cellText(r, 3))) + } else { + key = append(key, quoteIdent(cellText(r, 3))+desc(cellText(r, 4))) + } + } + fmt.Fprintf(&out, "\nCREATE %s%s INDEX %s ON %s (%s)", + unique, cellText(g.rows[0], 2), quoteIdent(g.key), target, strings.Join(key, ", ")) + if len(include) > 0 { + out.WriteString(" INCLUDE (" + strings.Join(include, ", ") + ")") + } + if filter := cellText(g.rows[0], 6); filter != "" { + out.WriteString(" WHERE " + filter) + } + out.WriteString(";\n") + } + + foreignKeys, err := s.metadata(ctx, `SELECT fk.name, SCHEMA_NAME(rt.schema_id), rt.name, pc.name, rc.name, + fk.delete_referential_action_desc, fk.update_referential_action_desc + FROM sys.foreign_keys fk + JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id + JOIN sys.objects rt ON rt.object_id = fk.referenced_object_id + JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id + AND pc.column_id = fkc.parent_column_id + JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id + AND rc.column_id = fkc.referenced_column_id + WHERE fk.parent_object_id = `+object+` + ORDER BY fk.name, fkc.constraint_column_id`) + if err != nil { + return "", err + } + for _, g := range groupByFirst(foreignKeys) { + cols := func(i int) string { + names := make([]string, len(g.rows)) + for j, r := range g.rows { + names[j] = quoteIdent(cellText(r, i)) + } + return strings.Join(names, ", ") + } + first := g.rows[0] + fmt.Fprintf(&out, "\nALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s.%s (%s)", + target, quoteIdent(g.key), cols(3), quoteIdent(cellText(first, 1)), quoteIdent(cellText(first, 2)), cols(4)) + for _, ev := range []struct{ event, action string }{ + {"DELETE", cellText(first, 5)}, + {"UPDATE", cellText(first, 6)}, + } { + if ev.action != "NO_ACTION" && ev.action != "" { + out.WriteString(" ON " + ev.event + " " + strings.ReplaceAll(ev.action, "_", " ")) + } + } + out.WriteString(";\n") + } + + triggers, err := s.metadata(ctx, `SELECT OBJECT_DEFINITION(object_id) FROM sys.triggers + WHERE parent_id = `+object+` ORDER BY name`) + if err != nil { + return "", err + } + var bodies []string + for _, r := range triggers { + if def := cellText(r, 0); strings.TrimSpace(def) != "" { + bodies = append(bodies, def) + } + } + if len(bodies) > 0 { + out.WriteString("GO\n") + for _, t := range bodies { + out.WriteString("\n" + strings.TrimSpace(t) + "\nGO\n") + } + } + return out.String(), nil +} + +type rowGroup struct { + key string + rows [][]*string +} + +// groupByFirst groups consecutive rows sharing their first column (catalog +// rows ordered by name). +func groupByFirst(rows [][]*string) []rowGroup { + var groups []rowGroup + for _, r := range rows { + key := cellText(r, 0) + if n := len(groups); n > 0 && groups[n-1].key == key { + groups[n-1].rows = append(groups[n-1].rows, r) + } else { + groups = append(groups, rowGroup{key: key, rows: [][]*string{r}}) + } + } + return groups +} + +func desc(isDescending string) string { + if isDescending == "true" { + return " DESC" + } + return "" +} diff --git a/internal/drivers/sqlserver/edit.go b/internal/drivers/sqlserver/edit.go new file mode 100644 index 0000000..c5e536f --- /dev/null +++ b/internal/drivers/sqlserver/edit.go @@ -0,0 +1,637 @@ +package sqlserver + +import ( + "context" + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +const onlyTableRows = "Read-only: only rows from a table can be edited." + +// describeSQL describes the first result set of @P1 in browse mode (base +// tables, hidden key columns) and lists the unique keys of the tables it +// reads, in one call. Describe errors come back as rows, not as raised +// errors. A transaction opened only by this call (manual-commit mode) is +// ended here. +const describeSQL = `DECLARE @lq_tc int = @@TRANCOUNT; +DECLARE @lq_d TABLE (ord int, hidden bit, other_db bit, sch nvarchar(128), tab nvarchar(128), + col nvarchar(128), type_name nvarchar(256), computed bit, err nvarchar(4000)); +INSERT INTO @lq_d +SELECT column_ordinal, is_hidden, + CASE WHEN source_server IS NOT NULL OR source_database <> DB_NAME() THEN 1 ELSE 0 END, + source_schema, source_table, source_column, + COALESCE(system_type_name, CASE WHEN user_type_schema = N'sys' THEN user_type_name END), + is_computed_column, error_message +FROM sys.dm_exec_describe_first_result_set(@P1, NULL, 1); +SELECT hidden, other_db, sch, tab, col, type_name, computed, err FROM @lq_d ORDER BY ord; +SELECT o.sch, o.tab, i.index_id, i.is_primary_key, c.name, c.is_nullable +FROM (SELECT DISTINCT sch, tab FROM @lq_d WHERE tab IS NOT NULL AND other_db = 0) o +JOIN sys.indexes i ON i.object_id = OBJECT_ID(QUOTENAME(o.sch) + N'.' + QUOTENAME(o.tab)) +JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id + AND ic.key_ordinal > 0 +JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id +WHERE i.is_unique = 1 AND i.has_filter = 0 AND i.is_disabled = 0 AND i.is_hypothetical = 0 +ORDER BY o.sch, o.tab, i.is_primary_key DESC, i.index_id, ic.key_ordinal; +IF @@TRANCOUNT > @lq_tc COMMIT TRAN;` + +// described is one result column as the server describes it. +type described struct { + // hidden: a key column added by browse mode, not part of the result. + hidden bool + // otherDB: comes from another database or a linked server. + otherDB bool + schema *string + table *string + column *string + typeName *string + computed bool + err *string +} + +// keyPart is one column of a unique index of a source table. +type keyPart struct { + schema string + table string + index int64 + primary bool + column string + nullable bool +} + +// detectEdit decides whether the rows of a result can be edited: the +// server describes the query and reports the source table's unique keys. +// Any failure only makes the result read-only; an empty reason comes with +// a target. +func (s *Session) detectEdit(sql string, columns int, state after) (*model.EditTarget, string) { + if !rowLimitApplies(sql) { + return nil, onlyTableRows + } + for _, w := range sqlWords(sql) { + if w == "UNION" || w == "EXCEPT" || w == "INTERSECT" { + return nil, "Read-only: the result combines several queries." + } + } + if state.xactState == -1 { + return nil, "Read-only: the transaction must be rolled back first." + } + sets, err := fetchAll(context.Background(), s.conn, describeSQL, &sql) + if err != nil { + // Only marks the session broken when the stream failed. + s.fail(err, "", false) + return nil, onlyTableRows + } + var desc []described + var keys []keyPart + if len(sets) > 0 { + for _, r := range sets[0] { + desc = append(desc, described{ + hidden: flag(r, 0), + otherDB: flag(r, 1), + schema: cell(r, 2), + table: cell(r, 3), + column: cell(r, 4), + typeName: cell(r, 5), + computed: flag(r, 6), + err: cell(r, 7), + }) + } + } + if len(sets) > 1 { + for _, r := range sets[1] { + index, _ := strconv.ParseInt(cellText(r, 2), 10, 64) + keys = append(keys, keyPart{ + schema: cellText(r, 0), + table: cellText(r, 1), + index: index, + primary: flag(r, 3), + column: cellText(r, 4), + nullable: flag(r, 5), + }) + } + } + return editTarget(desc, keys, columns) +} + +func eq(p *string, v string) bool { return p != nil && *p == v } + +// editTarget finds the table behind a result, or says why its rows cannot +// be edited. +func editTarget(desc []described, keys []keyPart, resultColumns int) (*model.EditTarget, string) { + for _, c := range desc { + if c.err != nil { + return nil, onlyTableRows + } + } + var visible []described + for _, c := range desc { + if !c.hidden { + visible = append(visible, c) + } + } + if len(visible) == 0 || len(visible) != resultColumns { + return nil, onlyTableRows + } + var schema, table string + found := false + for _, c := range visible { + if c.schema == nil || c.table == nil || c.column == nil { + continue + } + if c.otherDB { + return nil, "Read-only: the table is in another database." + } + if !found { + schema, table, found = *c.schema, *c.table, true + } else if *c.schema != schema || *c.table != table { + return nil, "Read-only: the result combines columns from several tables." + } + } + if !found { + return nil, onlyTableRows + } + ofTable := func(c described) bool { return eq(c.schema, schema) && eq(c.table, table) } + + // Plain, writable columns of the table; a repeated column is edited + // through its first occurrence only. + columns := make([]*model.EditColumn, 0, len(visible)) + var seen []string + for _, c := range visible { + var editable *model.EditColumn + if c.column != nil && c.typeName != nil && ofTable(c) && !c.computed && !slices.Contains(seen, *c.column) { + if _, err := valueExpr(*c.typeName, 1); err == nil { + seen = append(seen, *c.column) + editable = &model.EditColumn{Name: *c.column, TypeName: *c.typeName} + } + } + columns = append(columns, editable) + } + + // Unique indexes of the table, in the order the server listed them + // (primary key first). + type candidate struct { + primary bool + parts []keyPart + } + var candidates []candidate + for _, k := range keys { + if k.schema != schema || k.table != table { + continue + } + if n := len(candidates); n > 0 && candidates[n-1].parts[0].index == k.index { + candidates[n-1].parts = append(candidates[n-1].parts, k) + } else { + candidates = append(candidates, candidate{primary: k.primary, parts: []keyPart{k}}) + } + } + primary := false + for _, c := range candidates { + primary = primary || c.primary + } + kept := candidates[:0] + for _, c := range candidates { + if primary { + if c.primary { + kept = append(kept, c) + } + continue + } + notNull := true + for _, k := range c.parts { + notNull = notNull && !k.nullable + } + if notNull { + kept = append(kept, c) + } + } + candidates = kept + if len(candidates) == 0 { + return nil, fmt.Sprintf("Read-only: table %s has no primary key.", table) + } + for _, c := range candidates { + key := make([]int, 0, len(c.parts)) + for _, k := range c.parts { + pos := slices.IndexFunc(columns, func(col *model.EditColumn) bool { return col != nil && col.Name == k.column }) + if pos < 0 { + key = nil + break + } + key = append(key, pos) + } + if key == nil { + continue + } + // A key shown twice, or one browse mode had to add, means the table + // appears more than once (a self join): rows would be ambiguous. + for _, k := range c.parts { + shown := 0 + for _, v := range visible { + if ofTable(v) && eq(v.column, k.column) { + shown++ + } + } + added := false + for _, d := range desc { + if d.hidden && ofTable(d) && eq(d.column, k.column) { + added = true + } + } + if shown > 1 || added { + return nil, fmt.Sprintf("Read-only: the result shows table %s more than once.", table) + } + } + sch := schema + return &model.EditTarget{Schema: &sch, Table: table, Columns: columns, Key: key}, "" + } + names := make([]string, len(candidates[0].parts)) + for i, k := range candidates[0].parts { + names[i] = k.column + } + what := "key" + if 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, ", ")) +} + +// parseType returns the base name (lowercase) and arguments of a type such +// as decimal(10,2); ok is false when the text is not a plain type name. +func parseType(typeName string) (base string, args []string, ok bool) { + t := strings.TrimSpace(typeName) + rest := "" + hasArgs := false + if i := strings.IndexByte(t, '('); i >= 0 { + base, rest, hasArgs = strings.TrimSpace(t[:i]), t[i+1:], true + var found bool + rest, found = strings.CutSuffix(rest, ")") + if !found { + return "", nil, false + } + } else { + base = t + } + if base == "" { + return "", nil, false + } + for _, c := range base { + if c != '_' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') { + return "", nil, false + } + } + if hasArgs { + for _, p := range strings.Split(rest, ",") { + p = strings.ToLower(strings.TrimSpace(p)) + if p != "max" && (p == "" || strings.Trim(p, "0123456789") != "") { + return "", nil, false + } + args = append(args, p) + } + } + return strings.ToLower(base), args, true +} + +func isBinaryType(base string) bool { + switch base { + case "binary", "varbinary", "image", "hierarchyid", "geometry", "geography": + return true + } + return false +} + +// valueExpr is the SQL that converts parameter @P{n} (text in the driver's +// display format) to the column type. Styles are explicit, so DATEFORMAT and +// LANGUAGE never change the result. +func valueExpr(typeName string, n int) (string, error) { + unsupported := apperr.Invalidf("Columns of type %s cannot be edited.", typeName) + base, args, ok := parseType(typeName) + if !ok { + return "", unsupported + } + ty := base + if len(args) > 0 { + ty = base + "(" + strings.Join(args, ",") + ")" + } + p := "@P" + strconv.Itoa(n) + switch base { + // Plain-text forms of these types do not depend on session settings; + // bit takes true/false or 1/0. + case "bit", "tinyint", "smallint", "int", "bigint", "decimal", "numeric", "money", + "smallmoney", "float", "real", "uniqueidentifier", "time": + return "CAST(" + p + " AS " + ty + ")", nil + // ODBC canonical (yyyy-mm-dd hh:mi:ss.fffffff [+hh:mm]). + case "date", "datetime", "datetime2", "smalldatetime", "datetimeoffset": + return "CONVERT(" + ty + ", " + p + ", 121)", nil + // The nvarchar parameter converts to the column on assignment. + case "char", "varchar", "text", "nchar", "nvarchar", "ntext", "sysname", "xml": + return p, nil + // Style 1: 0x-prefixed hexadecimal. + case "binary", "varbinary": + return "CONVERT(" + ty + ", " + p + ", 1)", nil + case "image": + return "CONVERT(varbinary(max), " + p + ", 1)", nil + case "hierarchyid", "geometry", "geography": + return "CAST(CONVERT(varbinary(max), " + p + ", 1) AS " + ty + ")", nil + } + // timestamp/rowversion, sql_variant, user CLR types. + return "", unsupported +} + +type changeOp int + +const ( + opUpdate changeOp = iota + opDelete + opInsert +) + +// changeSQL is one statement of an apply with its parameters (@P1...). +type changeSQL struct { + op changeOp + sql string + params []*string +} + +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("Column %d of the result cannot be edited.", index+1) +} + +// bind adds a value as a parameter and returns the expression that +// converts it. +func bind(params *[]*string, column *model.EditColumn, value *string) (string, error) { + if value != nil { + if base, _, ok := parseType(column.TypeName); ok && isBinaryType(base) && strings.Contains(*value, previewMark) { + return "", apperr.Invalidf("This value is only a preview and cannot be saved.") + } + } + *params = append(*params, value) + return valueExpr(column.TypeName, len(*params)) +} + +func whereKey(target *model.EditTarget, key []*string, params *[]*string) (string, error) { + if len(key) != len(target.Key) { + return "", apperr.Invalidf("The row key does not match 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 + } + expr, err := bind(params, column, key[i]) + if err != nil { + return "", err + } + parts = append(parts, name+" = "+expr) + } + return strings.Join(parts, " AND "), nil +} + +type assignment struct { + column *model.EditColumn + value *string +} + +// assignments are the edited values by table column, the last one winning. +func assignments(target *model.EditTarget, values []model.CellValue) ([]assignment, error) { + var out []assignment + for _, v := range values { + column, err := targetColumn(target, v.Column) + if err != nil { + return nil, err + } + if i := slices.IndexFunc(out, func(a assignment) bool { return a.column.Name == column.Name }); i >= 0 { + out[i].value = v.Value + } else { + out = append(out, assignment{column, v.Value}) + } + } + return out, nil +} + +// buildChange writes the statement of one grid change; nil for an update +// with nothing to set. +func buildChange(target *model.EditTarget, change model.RowChange, identity []string) (*changeSQL, error) { + table := qualified(target.Schema, target.Table) + var params []*string + switch change.Op { + case model.OpUpdate: + values, err := assignments(target, change.Values) + if err != nil { + return nil, err + } + if len(values) == 0 { + return nil, nil + } + sets := make([]string, 0, len(values)) + for _, a := range values { + if slices.Contains(identity, a.column.Name) { + return nil, apperr.Invalidf("Column %s is an identity column and cannot be changed.", a.column.Name) + } + expr, err := bind(¶ms, a.column, a.value) + if err != nil { + return nil, err + } + sets = append(sets, quoteIdent(a.column.Name)+" = "+expr) + } + filter, err := whereKey(target, change.Key, ¶ms) + if err != nil { + return nil, err + } + return &changeSQL{op: opUpdate, sql: "UPDATE " + table + " SET " + strings.Join(sets, ", ") + " WHERE " + filter, params: params}, nil + case model.OpDelete: + filter, err := whereKey(target, change.Key, ¶ms) + if err != nil { + return nil, err + } + return &changeSQL{op: opDelete, sql: "DELETE FROM " + table + " WHERE " + filter, params: params}, nil + case model.OpInsert: + values, err := assignments(target, change.Values) + if err != nil { + return nil, err + } + var names, exprs []string + for _, a := range values { + if slices.Contains(identity, a.column.Name) { + if a.value == nil { + continue + } + return nil, apperr.Invalidf("Column %s is an identity column: leave it empty so the server numbers the row (an explicit value needs IDENTITY_INSERT).", a.column.Name) + } + expr, err := bind(¶ms, a.column, a.value) + if err != nil { + return nil, err + } + exprs = append(exprs, expr) + names = append(names, quoteIdent(a.column.Name)) + } + sql := "INSERT INTO " + table + " DEFAULT VALUES" + if len(names) > 0 { + sql = "INSERT INTO " + table + " (" + strings.Join(names, ", ") + ") VALUES (" + strings.Join(exprs, ", ") + ")" + } + return &changeSQL{op: opInsert, sql: sql, params: params}, nil + } + return nil, apperr.Invalidf("Unknown change %q.", change.Op) +} + +// ApplyChanges applies grid edits as one unit. With no transaction open, +// they run in one that commits (autocommit) or stays open (manual commit). +// Inside an open transaction they run after a savepoint, so a failure undoes +// only them. +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + target := &req.Target + table := qualified(target.Schema, target.Table) + autocommit := s.TxState().Autocommit + started := time.Now() + + // State, identity columns, and the transaction or savepoint in one + // trip. Sent as a plain batch: BEGIN TRAN inside sp_executesql would + // change the transaction count of the call. + start := `DECLARE @lq_tc int = @@TRANCOUNT, @lq_xs int = XACT_STATE(); + SELECT @lq_tc, @lq_xs; + SELECT name FROM sys.identity_columns WHERE object_id = OBJECT_ID(` + nstr(table) + `); + IF @lq_xs = 1 SAVE TRAN lq_apply; + ELSE IF @lq_xs = 0 AND @@TRANCOUNT = 0 BEGIN TRAN;` + sets, err := fetchAll(opCtx, s.conn, start) + if err != nil { + return nil, s.callErr(err) + } + var stateRows [][]*string + if len(sets) > 0 { + stateRows = sets[0] + } + trancount, xactState := intAt(stateRows, 0), intAt(stateRows, 1) + if xactState == -1 { + return nil, doomed() + } + var identity []string + if len(sets) > 1 { + for _, r := range sets[1] { + if v := cell(r, 0); v != nil { + identity = append(identity, *v) + } + } + } + // Whether this call opened the transaction (or the implicit one). + fresh := trancount == 0 + + result, outcome := s.runChanges(opCtx, req, identity) + var end string + switch { + // A commit that cannot complete is rolled back and reported. + case outcome == nil && fresh && autocommit: + end = `DECLARE @lq_ok int = 1; + WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; + IF @@TRANCOUNT > 0 BEGIN SET @lq_ok = 0; ROLLBACK TRAN; END; + SELECT @@TRANCOUNT, XACT_STATE(), @lq_ok` + case outcome == nil: + end = "SELECT @@TRANCOUNT, XACT_STATE(), 1" + // Everything since the start belongs to this call. + case fresh: + end = "IF @@TRANCOUNT > 0 ROLLBACK TRAN; SELECT @@TRANCOUNT, XACT_STATE(), 0" + default: + end = `IF XACT_STATE() = 1 ROLLBACK TRAN lq_apply; + SELECT @@TRANCOUNT, XACT_STATE(), 0` + } + // Transaction count, XACT_STATE() and whether the commit completed. The + // end runs even when the call was cancelled. + var endRows [][]*string + ended := false + if !s.broken.Load() { + rows, err := fetch(context.Background(), s.conn, end) + if err != nil { + e := s.fail(err, "", false) + if outcome == nil { + return nil, e + } + } else { + endRows, ended = rows, true + } + } + if ended { + s.setInTransaction(intAt(endRows, 0) > 0) + } + if outcome != nil { + if ended && intAt(endRows, 1) == -1 { + e := *outcome + e.Hint = "The transaction can no longer be committed; roll it back." + return nil, &e + } + return nil, outcome + } + if ended && intAt(endRows, 2) == 0 { + return nil, apperr.New(apperr.Database, "The changes could not be committed and were rolled back.") + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.InTransaction = s.TxState().InTransaction + return result, nil +} + +// runChanges runs every change; it stops at the first failure. +func (s *Session) runChanges(ctx context.Context, req model.ApplyRequest, identity []string) (*model.ApplyResult, *apperr.Error) { + statements := make([]*changeSQL, len(req.Changes)) + for i, c := range req.Changes { + st, err := buildChange(&req.Target, c, identity) + if err != nil { + return nil, apperr.From(err) + } + statements[i] = st + } + result := &model.ApplyResult{} + for i, st := range statements { + if st == nil { + continue + } + row := i + 1 + sets, err := fetchAll(ctx, s.conn, st.sql+";\nSELECT ROWCOUNT_BIG();", st.params...) + if err != nil { + e := s.callErr(err) + if e.Kind != apperr.Cancelled { + c := *e + c.Position = nil + c.Detail = fmt.Sprintf("Row %d was not saved.", row) + e = &c + } + return nil, e + } + var count int64 + if len(sets) > 0 { + count = intAt(sets[len(sets)-1], 0) + } + switch st.op { + case opInsert: + result.Inserted++ + default: + if count != 1 { + why := fmt.Sprintf("%d rows matched its key", count) + if count == 0 { + why = "0 rows matched its key (changed or removed by someone else)" + } + return nil, apperr.Newf(apperr.Database, "Row %d was not saved: %s.", row, why) + } + if st.op == opUpdate { + result.Updated++ + } else { + result.Deleted++ + } + } + } + return result, nil +} diff --git a/internal/drivers/sqlserver/edit_test.go b/internal/drivers/sqlserver/edit_test.go new file mode 100644 index 0000000..2b0c68a --- /dev/null +++ b/internal/drivers/sqlserver/edit_test.go @@ -0,0 +1,230 @@ +package sqlserver + +import ( + "reflect" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func col(table, column, ty string) described { + return described{schema: str("dbo"), table: str(table), column: str(column), typeName: str(ty)} +} + +func expr(ty string) described { return described{typeName: str(ty)} } + +func key(table string, index int64, primary bool, column string, nullable bool) keyPart { + return keyPart{schema: "dbo", table: table, index: index, primary: primary, column: column, nullable: nullable} +} + +func TestDetectionFindsTableAndKey(t *testing.T) { + computed := col("t", "total", "int") + computed.computed = true + desc := []described{ + col("t", "name", "nvarchar(40)"), + expr("int"), + col("t", "b", "int"), + col("t", "a", "int"), + computed, + col("t", "ver", "timestamp"), + } + keys := []keyPart{key("t", 1, true, "a", false), key("t", 1, true, "b", false)} + target, reason := editTarget(desc, keys, 6) + if target == nil { + t.Fatal(reason) + } + if *target.Schema != "dbo" || target.Table != "t" || !reflect.DeepEqual(target.Key, []int{3, 2}) { + t.Errorf("%+v", target) + } + if c := target.Columns[0]; c == nil || c.Name != "name" || c.TypeName != "nvarchar(40)" { + t.Errorf("column 0: %+v", c) + } + if target.Columns[1] != nil || target.Columns[4] != nil || target.Columns[5] != nil { + t.Error("expression, computed and rowversion columns must be read-only") + } +} + +func TestDetectionReadOnlyReasons(t *testing.T) { + pk := []keyPart{key("t", 1, true, "id", false)} + readOnly := func(desc []described, keys []keyPart, n int) string { + t.Helper() + target, reason := editTarget(desc, keys, n) + if target != nil { + t.Fatalf("editable: %+v", target) + } + return reason + } + if r := readOnly([]described{col("t", "id", "int"), col("u", "id", "int")}, pk, 2); !strings.Contains(r, "several tables") { + t.Error(r) + } + if r := readOnly([]described{expr("int")}, pk, 1); r != onlyTableRows { + t.Error(r) + } + if r := readOnly([]described{{err: str("uses a temp table")}}, pk, 1); r != onlyTableRows { + t.Error(r) + } + // Column count does not match the result. + readOnly([]described{col("t", "id", "int")}, pk, 2) + // Key missing; browse mode added it as a hidden column. + hidden := col("t", "id", "int") + hidden.hidden = true + if r := readOnly([]described{col("t", "name", "nvarchar(5)"), hidden}, pk, 1); r != "Read-only: add the primary key columns (id) to the query to edit rows." { + t.Error(r) + } + // No key at all; a unique index on a nullable column does not count. + if r := readOnly([]described{col("t", "id", "int")}, []keyPart{key("t", 2, false, "id", true)}, 1); r != "Read-only: table t has no primary key." { + t.Error(r) + } + // A NOT NULL unique key is used when there is no primary key. + target, reason := editTarget([]described{col("t", "x", "int"), col("t", "code", "varchar(5)")}, + []keyPart{key("t", 2, false, "code", false)}, 2) + if target == nil || !reflect.DeepEqual(target.Key, []int{1}) { + t.Errorf("%+v %s", target, reason) + } + // Another database. + other := col("t", "id", "int") + other.otherDB = true + if r := readOnly([]described{other}, pk, 1); !strings.Contains(r, "another database") { + t.Error(r) + } + // Self join: the key shows twice. + if r := readOnly([]described{col("t", "id", "int"), col("t", "id", "int")}, pk, 2); !strings.Contains(r, "more than once") { + t.Error(r) + } + // Self join: browse mode added the other instance's key. + if r := readOnly([]described{col("t", "id", "int"), col("t", "name", "int"), hidden}, pk, 2); !strings.Contains(r, "more than once") { + t.Error(r) + } +} + +func TestValuesConvertWithFixedStyles(t *testing.T) { + cases := map[string]string{ + "decimal(10, 2)": "CAST(@P2 AS decimal(10,2))", + "BIT": "CAST(@P2 AS bit)", + "datetime2(7)": "CONVERT(datetime2(7), @P2, 121)", + "datetimeoffset(3)": "CONVERT(datetimeoffset(3), @P2, 121)", + "datetime": "CONVERT(datetime, @P2, 121)", + "time(3)": "CAST(@P2 AS time(3))", + "varbinary(max)": "CONVERT(varbinary(max), @P2, 1)", + "binary(4)": "CONVERT(binary(4), @P2, 1)", + "image": "CONVERT(varbinary(max), @P2, 1)", + "hierarchyid": "CAST(CONVERT(varbinary(max), @P2, 1) AS hierarchyid)", + "nvarchar(40)": "@P2", + "uniqueidentifier": "CAST(@P2 AS uniqueidentifier)", + } + for ty, want := range cases { + got, err := valueExpr(ty, 2) + if err != nil || got != want { + t.Errorf("%s: %q %v", ty, got, err) + } + } + for _, bad := range []string{"timestamp", "sql_variant", "int); DROP TABLE x; --", "decimal(10,2", "varchar(-1)", ""} { + if _, err := valueExpr(bad, 1); err == nil { + t.Errorf("%q accepted", bad) + } + } +} + +func target() *model.EditTarget { + c := func(name, ty string) *model.EditColumn { return &model.EditColumn{Name: name, TypeName: ty} } + return &model.EditTarget{ + Schema: str("dbo"), + Table: "Order Items", + Columns: []*model.EditColumn{ + c("Item Id", "int"), + c("name", "nvarchar(40)"), + nil, + c("data", "varbinary(max)"), + c("code", "char(3)"), + }, + Key: []int{0, 4}, + } +} + +func cv(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func TestChangeStatements(t *testing.T) { + tg := target() + s, err := buildChange(tg, model.RowChange{ + Op: model.OpUpdate, + Key: []*string{str("7"), nil}, + Values: []model.CellValue{cv(1, str("it's")), cv(3, nil)}, + }, nil) + if err != nil { + t.Fatal(err) + } + if s.op != opUpdate || s.sql != "UPDATE [dbo].[Order Items] SET [name] = @P1, [data] = CONVERT(varbinary(max), @P2, 1) "+ + "WHERE [Item Id] = CAST(@P3 AS int) AND [code] IS NULL" { + t.Errorf("%s", s.sql) + } + if !reflect.DeepEqual(s.params, []*string{str("it's"), nil, str("7")}) { + t.Errorf("params %v", s.params) + } + + s, err = buildChange(tg, model.RowChange{Op: model.OpDelete, Key: []*string{str("7"), str("ab ")}}, nil) + if err != nil || s.sql != "DELETE FROM [dbo].[Order Items] WHERE [Item Id] = CAST(@P1 AS int) AND [code] = @P2" { + t.Errorf("%v %v", s, err) + } + + s, err = buildChange(tg, model.RowChange{ + Op: model.OpInsert, + Values: []model.CellValue{cv(1, str("a")), cv(1, str("b")), cv(0, nil)}, + }, []string{"Item Id"}) + if err != nil || s.op != opInsert || s.sql != "INSERT INTO [dbo].[Order Items] ([name]) VALUES (@P1)" || + !reflect.DeepEqual(s.params, []*string{str("b")}) { + t.Errorf("%+v %v", s, err) + } + + s, err = buildChange(tg, model.RowChange{Op: model.OpInsert}, nil) + if err != nil || s.sql != "INSERT INTO [dbo].[Order Items] DEFAULT VALUES" { + t.Errorf("%+v %v", s, err) + } + + // Nothing to set. + s, err = buildChange(tg, model.RowChange{Op: model.OpUpdate, Key: []*string{str("1"), str("x")}}, nil) + if err != nil || s != nil { + t.Errorf("%+v %v", s, err) + } +} + +func TestInvalidChangesAreRejected(t *testing.T) { + tg := target() + k := []*string{str("1"), str("x")} + invalid := func(change model.RowChange, identity []string) string { + t.Helper() + _, err := buildChange(tg, change, identity) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Invalid { + t.Fatalf("error %v", err) + } + return e.Message + } + // Expression column. + if m := invalid(model.RowChange{Op: model.OpUpdate, Key: k, Values: []model.CellValue{cv(2, str("1"))}}, nil); !strings.Contains(m, "Column 3") { + t.Error(m) + } + // Truncated binary preview. + if m := invalid(model.RowChange{Op: model.OpUpdate, Key: k, Values: []model.CellValue{cv(3, str("0x00FF… (40000 bytes)"))}}, nil); m != "This value is only a preview and cannot be saved." { + t.Error(m) + } + // Identity value on insert and identity change on update. + id := []string{"Item Id"} + if m := invalid(model.RowChange{Op: model.OpInsert, Values: []model.CellValue{cv(0, str("5"))}}, id); !strings.Contains(m, "IDENTITY_INSERT") { + t.Error(m) + } + if m := invalid(model.RowChange{Op: model.OpUpdate, Key: k, Values: []model.CellValue{cv(0, str("5"))}}, id); !strings.Contains(m, "identity") { + t.Error(m) + } + // Key of the wrong length. + invalid(model.RowChange{Op: model.OpDelete, Key: []*string{str("1")}}, nil) + // Unknown operation. + invalid(model.RowChange{Op: "upsert"}, nil) + // Text that only looks like a preview is fine. + if _, err := buildChange(tg, model.RowChange{Op: model.OpUpdate, Key: k, Values: []model.CellValue{cv(1, str("see… (below)"))}}, nil); err != nil { + t.Error(err) + } +} diff --git a/internal/drivers/sqlserver/integration_test.go b/internal/drivers/sqlserver/integration_test.go new file mode 100644 index 0000000..7c5490d --- /dev/null +++ b/internal/drivers/sqlserver/integration_test.go @@ -0,0 +1,710 @@ +package sqlserver + +// Tests against a real server. They only run with LQ_MSSQL_HOST set (and +// optionally LQ_MSSQL_PORT, LQ_MSSQL_USER, LQ_MSSQL_PASSWORD, LQ_MSSQL_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 testProfile(t *testing.T) (model.ConnectionProfile, string) { + t.Helper() + host := os.Getenv("LQ_MSSQL_HOST") + if host == "" { + t.Skip("LQ_MSSQL_HOST is not set") + } + p := model.DefaultProfile() + p.Name = "test" + p.Engine = model.SQLServer + p.Host = host + p.Port = 1433 + if port, err := strconv.ParseUint(os.Getenv("LQ_MSSQL_PORT"), 10, 16); err == nil { + p.Port = uint16(port) + } + p.User = env("LQ_MSSQL_USER", "sa") + p.Database = env("LQ_MSSQL_DB", "master") + p.SslMode = model.SslPrefer + return p, os.Getenv("LQ_MSSQL_PASSWORD") +} + +func mssqlSession(t *testing.T) *Session { + t.Helper() + p, password := testProfile(t) + s, err := Connect(context.Background(), p, &password) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func run(s *Session, sql string, maxRows int) (*model.ExecResult, error) { + return s.Execute(context.Background(), model.ExecRequest{SQL: sql, MaxRows: maxRows}) +} + +func exec(t *testing.T, s *Session, sql string, maxRows int) *model.ExecResult { + t.Helper() + r, err := run(s, sql, maxRows) + if err != nil { + t.Fatalf("%s: %v", sql, err) + } + return r +} + +// 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 scalar(t *testing.T, s *Session, sql string) string { + t.Helper() + return texts(exec(t, s, sql, 0).Rows)[0][0] +} + +func reason(t *testing.T, r *model.ExecResult) string { + t.Helper() + if r.Editable != nil { + t.Fatal("unexpectedly editable") + } + if r.ReadOnlyReason == nil { + t.Fatal("no read-only reason") + } + return *r.ReadOnlyReason +} + +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 update(key string, values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: []*string{str(key)}, Values: values} +} + +func remove(key string) model.RowChange { + return model.RowChange{Op: model.OpDelete, Key: []*string{str(key)}} +} + +func insert(values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpInsert, Values: values} +} + +func setAutocommit(t *testing.T, s *Session, on bool) model.TxState { + t.Helper() + st, err := s.SetAutocommit(context.Background(), on) + if err != nil { + t.Fatal(err) + } + return st +} + +func endTransaction(t *testing.T, s *Session, commit bool) model.TxState { + t.Helper() + st, err := s.EndTransaction(context.Background(), commit) + if err != nil { + t.Fatal(err) + } + return st +} + +func TestMssqlSessionInfo(t *testing.T) { + s := mssqlSession(t) + if !strings.HasPrefix(s.ServerVersion(), "SQL Server ") { + t.Errorf("version %q", s.ServerVersion()) + } + if s.CurrentUser() == nil || s.CurrentSchema() == nil || *s.CurrentSchema() != "dbo" { + t.Errorf("user %v, schema %v", s.CurrentUser(), s.CurrentSchema()) + } + p, _ := testProfile(t) + wrong := "wrong-password" + _, err := Connect(context.Background(), p, &wrong) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Connection || e.Code != "Msg 18456, Level 14, State 1" { + t.Errorf("wrong password: %+v", e) + } +} + +func TestMssqlFormatsValues(t *testing.T) { + s := mssqlSession(t) + r := exec(t, s, `SELECT CAST(12345.6789 AS decimal(18,4)), CAST(-0.5 AS numeric(5,2)), + CAST(123456789.1234 AS money), CAST(-12.5 AS smallmoney), + CAST(1 AS bit), CAST(0 AS bit), + CAST('2024-05-01 13:45:30.1234567' AS datetime2(7)), + CAST('2024-05-01 13:45:30.12' AS datetime2(2)), + CAST('2024-05-01T13:45:30.123+03:00' AS datetimeoffset(3)), + CAST('2024-05-01 13:45:30.997' AS datetime), + CAST('2024-05-01 13:45' AS smalldatetime), + CAST('2024-05-01' AS date), CAST('13:45:30.5' AS time(1)), + CAST('6f9619ff-8b86-d011-b42d-00c04fc964ff' AS uniqueidentifier), + 0x0A0BFF, CAST('1' AS xml), N'ação', CAST(NULL AS int), + CAST(1.5 AS float), CAST(9223372036854775807 AS bigint), + CAST(255 AS tinyint), CAST(-32768 AS smallint), CAST('x ' AS char(3)), + CAST(0.1 AS real), CAST(1e20 AS float)`, 0) + want := []string{ + "12345.6789", "-0.50", "123456789.1234", "-12.5000", "true", "false", + "2024-05-01 13:45:30.1234567", "2024-05-01 13:45:30.12", "2024-05-01 13:45:30.123 +03:00", + "2024-05-01 13:45:30.997", "2024-05-01 13:45:00", "2024-05-01", "13:45:30.5", + "6F9619FF-8B86-D011-B42D-00C04FC964FF", "0x0A0BFF", "1", "ação", "NULL", + "1.5", "9223372036854775807", "255", "-32768", "x ", "0.1", "1E+20", + } + if got := texts(r.Rows); len(got) != 1 || !reflect.DeepEqual(got[0], want) { + t.Errorf("values:\n got %q\nwant %q", got, want) + } + kinds := map[int]model.ValueKind{ + 0: model.KindNumber, 2: model.KindNumber, 4: model.KindBool, 6: model.KindTemporal, + 8: model.KindTemporal, 13: model.KindText, 14: model.KindBinary, 16: model.KindText, + } + 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[0].TypeName != "decimal" || r.Columns[6].TypeName != "datetime2" { + t.Errorf("type names %q %q", r.Columns[0].TypeName, r.Columns[6].TypeName) + } +} + +func TestMssqlRowLimit(t *testing.T) { + s := mssqlSession(t) + exec(t, s, "CREATE TABLE #lq_limit (id int)", 0) + r := exec(t, s, "INSERT INTO #lq_limit SELECT TOP (30) 1 FROM sys.all_objects", 0) + if r.RowsAffected == nil || *r.RowsAffected != 30 { + t.Errorf("insert: %v", r.RowsAffected) + } + if r = exec(t, s, "SELECT * FROM #lq_limit", 10); len(r.Rows) != 10 || !r.Truncated { + t.Errorf("limited: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + if r = exec(t, s, "SELECT TOP (10) * FROM #lq_limit", 10); len(r.Rows) != 10 || r.Truncated { + t.Errorf("exactly the limit: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + // ROWCOUNT was reset: the UPDATE touches every row. + if r = exec(t, s, "UPDATE #lq_limit SET id = 2", 10); r.RowsAffected == nil || *r.RowsAffected != 30 { + t.Errorf("update: %v", r.RowsAffected) + } + // Not a plain SELECT: limited on the client, rows still all inserted. + if r = exec(t, s, "SELECT * INTO #lq_copy FROM #lq_limit", 10); r.RowsAffected == nil || *r.RowsAffected != 30 { + t.Errorf("select into: %v", r.RowsAffected) + } + if r = exec(t, s, "EXEC('SELECT * FROM #lq_copy')", 5); len(r.Rows) != 5 || !r.Truncated { + t.Errorf("exec: %d rows, truncated %v", len(r.Rows), r.Truncated) + } +} + +func TestMssqlErrorsAndNotices(t *testing.T) { + s := mssqlSession(t) + _, err := run(s, "SELECT 1;\nSELECT * FROM dbo.lq_missing_table", 0) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || e.Code != "Msg 208, Level 16, State 1" || + e.Position == nil || *e.Position != 10 { + t.Errorf("error: %+v", e) + } + // The session keeps working. + if got := scalar(t, s, "SELECT 1"); got != "1" { + t.Errorf("after error: %s", got) + } + + // An error before any result set does not hang the session. + _, err = run(s, "RAISERROR('boom', 16, 1);\nSELECT 1", 0) + if e := apperr.From(err); e == nil || e.Code != "Msg 50000, Level 16, State 1" || e.Message != "boom" { + t.Errorf("raiserror: %+v", e) + } + if got := scalar(t, s, "SELECT 2"); got != "2" { + t.Errorf("after raiserror: %s", got) + } + + // PRINT and low-severity RAISERROR are notices. + r := exec(t, s, "PRINT 'hello'; RAISERROR('warn %d', 0, 1, 42) WITH NOWAIT; SELECT 3", 0) + if !reflect.DeepEqual(r.Notices, []string{"hello", "warn 42"}) || !reflect.DeepEqual(texts(r.Rows), [][]string{{"3"}}) { + t.Errorf("notices %q, rows %q", r.Notices, texts(r.Rows)) + } + // Many messages do not block the reader. + r = exec(t, s, "DECLARE @i int = 0; WHILE @i < 200 BEGIN PRINT @i; SET @i += 1 END; SELECT 4", 0) + if len(r.Notices) != 200 || !reflect.DeepEqual(texts(r.Rows), [][]string{{"4"}}) { + t.Errorf("%d notices, rows %q", len(r.Notices), texts(r.Rows)) + } + // A database change is not a notice. + if r = exec(t, s, "USE master", 0); len(r.Notices) != 0 { + t.Errorf("notices %q", r.Notices) + } + // A single word runs as a batch, not as a procedure call. + if r = exec(t, s, "sp_who", 0); len(r.Rows) == 0 { + t.Error("sp_who returned nothing") + } +} + +func TestMssqlManualTransactions(t *testing.T) { + s := mssqlSession(t) + exec(t, s, "CREATE TABLE #lq_tx (id int)", 0) + + if st := setAutocommit(t, s, false); st.Autocommit || st.InTransaction { + t.Errorf("manual: %+v", st) + } + if r := exec(t, s, "INSERT INTO #lq_tx VALUES (1)", 0); !r.InTransaction { + t.Error("insert not in a transaction") + } + if st := endTransaction(t, s, false); st.InTransaction { + t.Errorf("rollback: %+v", st) + } + if got := scalar(t, s, "SELECT COUNT(*) FROM #lq_tx"); got != "0" { + t.Errorf("count after rollback %s", got) + } + + exec(t, s, "INSERT INTO #lq_tx VALUES (2)", 0) + if st := endTransaction(t, s, true); st.InTransaction { + t.Errorf("commit: %+v", st) + } + + exec(t, s, "INSERT INTO #lq_tx VALUES (3)", 0) + if !s.TxState().InTransaction { + t.Error("no transaction") + } + // Back to autocommit commits pending work. + if st := setAutocommit(t, s, true); !st.Autocommit || st.InTransaction { + t.Errorf("autocommit: %+v", st) + } + r := exec(t, s, "SELECT COUNT(*) FROM #lq_tx", 0) + if texts(r.Rows)[0][0] != "2" || r.InTransaction { + t.Errorf("count %q, in transaction %v", texts(r.Rows), r.InTransaction) + } + + // Explicit BEGIN TRAN in autocommit mode is tracked too. + if r := exec(t, s, "BEGIN TRAN", 0); !r.InTransaction { + t.Error("BEGIN TRAN not tracked") + } + if r := exec(t, s, "ROLLBACK", 0); r.InTransaction { + t.Error("ROLLBACK not tracked") + } +} + +func TestMssqlMetadata(t *testing.T) { + s := mssqlSession(t) + ctx := context.Background() + exec(t, s, `DROP TABLE IF EXISTS dbo.lq_meta; + CREATE TABLE dbo.lq_meta (id int NOT NULL PRIMARY KEY, name nvarchar(40) NULL, + amount decimal(10,2), data varbinary(max), + at datetime2(3))`, 0) + t.Cleanup(func() { _, _ = run(s, "DROP TABLE IF EXISTS dbo.lq_meta", 0) }) + + schemas, err := s.ListSchemas(ctx) + if err != nil || len(schemas) == 0 || schemas[0] != "dbo" { + t.Errorf("schemas %q %v", schemas, err) + } + for _, name := range schemas { + if name == "db_owner" { + t.Error("role schema listed") + } + } + has := func(objects []model.DbObject, name, kind string) bool { + for _, o := range objects { + if o.Name == name && o.Kind == kind { + return true + } + } + return false + } + if objects, err := s.ListObjects(ctx, "dbo"); err != nil || !has(objects, "lq_meta", "table") { + t.Errorf("dbo objects: %v", err) + } + if objects, err := s.ListObjects(ctx, "sys"); err != nil || !has(objects, "objects", "view") { + t.Errorf("sys objects: %v", err) + } + cols, err := s.ListColumns(ctx, "dbo", "lq_meta") + if err != nil { + t.Fatal(err) + } + var types []string + for _, c := range cols { + types = append(types, c.TypeName) + } + if want := []string{"int", "nvarchar(40)", "decimal(10,2)", "varbinary(max)", "datetime2(3)"}; !reflect.DeepEqual(types, want) { + t.Errorf("types %q", types) + } + if !cols[0].PrimaryKey || cols[0].Nullable || cols[1].PrimaryKey || !cols[1].Nullable { + t.Errorf("columns %+v", cols[:2]) + } +} + +func TestMssqlCancel(t *testing.T) { + s := mssqlSession(t) + done := make(chan error, 1) + go func() { + _, err := run(s, "WAITFOR DELAY '00:00:30'", 0) + done <- err + }() + time.Sleep(time.Second) + 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") + } + if got := scalar(t, s, "SELECT 2"); got != "2" { + t.Errorf("after cancel: %s", got) + } +} + +func TestMssqlContextCancelsQuery(t *testing.T) { + s := mssqlSession(t) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + started := time.Now() + _, err := s.Execute(ctx, model.ExecRequest{SQL: "WAITFOR DELAY '00:00:30'"}) + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Errorf("error %v", err) + } + if time.Since(started) > 20*time.Second { + t.Errorf("took %v", time.Since(started)) + } + if got := scalar(t, s, "SELECT 3"); got != "3" { + t.Errorf("after cancel: %s", got) + } +} + +func TestMssqlStream(t *testing.T) { + s := mssqlSession(t) + sink := make(chan drivers.StreamEvent, 10) + total, err := s.Stream(context.Background(), `SELECT g, + CASE WHEN g = 1 THEN CAST(REPLICATE(CAST('a' AS varchar(max)), 40000) AS varbinary(max)) END + FROM (SELECT TOP (1234) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) g + FROM sys.all_objects a CROSS JOIN sys.all_objects b) x + ORDER BY 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 TestMssqlEditDetection(t *testing.T) { + s := mssqlSession(t) + exec(t, s, `DROP TABLE IF EXISTS dbo.lq_edit_items, dbo.lq_edit_owner, dbo.lq_edit_nokey; + CREATE TABLE dbo.lq_edit_items (id int NOT NULL PRIMARY KEY, name nvarchar(40), + qty int, total AS qty * 2, ver rowversion); + CREATE TABLE dbo.lq_edit_owner (id int NOT NULL PRIMARY KEY, item_id int); + CREATE TABLE dbo.lq_edit_nokey (a int, b int); + INSERT INTO dbo.lq_edit_items (id, name, qty) VALUES (1, N'a', 1); + INSERT INTO dbo.lq_edit_owner VALUES (1, 1); + INSERT INTO dbo.lq_edit_nokey VALUES (1, 2);`, 0) + t.Cleanup(func() { + _, _ = run(s, "DROP TABLE IF EXISTS dbo.lq_edit_items, dbo.lq_edit_owner, dbo.lq_edit_nokey", 0) + }) + + r := exec(t, s, "SELECT name, id, qty + 1 AS next, total, ver FROM dbo.lq_edit_items", 0) + tg := r.Editable + if tg == nil || r.ReadOnlyReason != nil { + t.Fatalf("not editable: %v", r.ReadOnlyReason) + } + if tg.Schema == nil || *tg.Schema != "dbo" || tg.Table != "lq_edit_items" || !reflect.DeepEqual(tg.Key, []int{1}) { + t.Errorf("target %+v", tg) + } + if c := tg.Columns[0]; c == nil || c.Name != "name" || c.TypeName != "nvarchar(40)" { + t.Errorf("name column %+v", c) + } + if c := tg.Columns[1]; c == nil || c.TypeName != "int" { + t.Errorf("id column %+v", c) + } + if tg.Columns[2] != nil || tg.Columns[3] != nil || tg.Columns[4] != nil { + t.Error("expression, computed and rowversion columns must be read-only") + } + + r = exec(t, s, `SELECT i.id, i.name, o.id AS owner FROM dbo.lq_edit_items i + JOIN dbo.lq_edit_owner o ON o.item_id = i.id`, 0) + if got := reason(t, r); !strings.Contains(got, "several tables") { + t.Errorf("join: %q", got) + } + // Only columns of one table from a join: editable. + r = exec(t, s, `SELECT i.id, i.name FROM dbo.lq_edit_items i + JOIN dbo.lq_edit_owner o ON o.item_id = i.id`, 0) + if r.Editable == nil { + t.Errorf("join of one table's columns: %v", r.ReadOnlyReason) + } + reason(t, exec(t, s, "SELECT a, b FROM dbo.lq_edit_nokey", 0)) + if got := reason(t, exec(t, s, "SELECT name, qty FROM dbo.lq_edit_items", 0)); !strings.Contains(got, "(id)") { + t.Errorf("missing key: %q", got) + } + reason(t, exec(t, s, "SELECT 1 AS x", 0)) + if got := reason(t, exec(t, s, "EXEC('SELECT id FROM dbo.lq_edit_items')", 0)); got != onlyTableRows { + t.Errorf("exec: %q", got) + } + // A limited query is still described. + if r = exec(t, s, "SELECT id, name FROM dbo.lq_edit_items", 1); r.Editable == nil { + t.Errorf("limited: %v", r.ReadOnlyReason) + } + + // Manual commit: describing never leaves a transaction behind. + setAutocommit(t, s, false) + if r = exec(t, s, "SELECT 1 AS x", 0); r.InTransaction { + t.Error("describing opened a transaction") + } + if got := scalar(t, s, "SELECT @@TRANCOUNT"); got != "0" { + t.Errorf("trancount %s", got) + } + if r = exec(t, s, "SELECT id, name FROM dbo.lq_edit_items", 0); r.Editable == nil { + t.Errorf("manual: %v", r.ReadOnlyReason) + } + endTransaction(t, s, false) + setAutocommit(t, s, true) +} + +func TestMssqlEditApply(t *testing.T) { + s := mssqlSession(t) + exec(t, s, `DROP TABLE IF EXISTS dbo.lq_edit_rows; + CREATE TABLE dbo.lq_edit_rows (id int IDENTITY PRIMARY KEY, + name nvarchar(40) NOT NULL, qty int NULL); + INSERT INTO dbo.lq_edit_rows (name, qty) VALUES (N'a', 1), (N'b', 2), (N'c', 3);`, 0) + t.Cleanup(func() { _, _ = run(s, "DROP TABLE IF EXISTS dbo.lq_edit_rows", 0) }) + + tg := exec(t, s, "SELECT id, name, qty FROM dbo.lq_edit_rows ORDER BY id", 0).Editable + if tg == nil { + t.Fatal("not editable") + } + res, err := apply(s, tg, update("1", cv(1, str("a2")), cv(2, nil)), remove("2"), insert(cv(1, str("d")), cv(0, nil))) + if err != nil { + t.Fatal(err) + } + if res.Updated != 1 || res.Deleted != 1 || res.Inserted != 1 || res.InTransaction { + t.Errorf("result %+v", res) + } + const all = `SELECT STRING_AGG(name + ':' + ISNULL(CAST(qty AS varchar(10)), 'null'), ',') + WITHIN GROUP (ORDER BY id) FROM dbo.lq_edit_rows` + check := func(want string) { + t.Helper() + if got := scalar(t, s, all); got != want { + t.Errorf("rows %q, want %q", got, want) + } + } + check("a2:null,c:3,d:null") + + // An identity value on insert is refused before anything runs. + _, err = apply(s, tg, insert(cv(0, str("50")), cv(1, str("x")))) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid { + t.Errorf("identity insert: %v", err) + } + if s.TxState().InTransaction { + t.Error("transaction left open") + } + + // A key that matches nothing rolls back the earlier changes. + _, err = apply(s, tg, update("1", cv(1, str("changed"))), update("999", cv(1, str("ghost")))) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Database || + e.Message != "Row 2 was not saved: 0 rows matched its key (changed or removed by someone else)." { + t.Errorf("missing key: %+v", e) + } + if s.TxState().InTransaction { + t.Error("transaction left open") + } + check("a2:null,c:3,d:null") + + // A server error (NOT NULL) maps like execute and rolls back. + _, err = apply(s, tg, remove("3"), update("1", cv(1, nil))) + if e := apperr.From(err); e == nil || e.Code != "Msg 515, Level 16, State 2" || e.Detail != "Row 2 was not saved." { + t.Errorf("not null: %+v", e) + } + check("a2:null,c:3,d:null") + + // Manual commit: the changes stay in the open transaction. + setAutocommit(t, s, false) + if res, err = apply(s, tg, update("1", cv(1, str("m1")))); err != nil || !res.InTransaction || !s.TxState().InTransaction { + t.Errorf("manual: %+v %v", res, err) + } + endTransaction(t, s, false) + check("a2:null,c:3,d:null") + endTransaction(t, s, true) + if _, err = apply(s, tg, update("1", cv(1, str("m2")))); err != nil { + t.Fatal(err) + } + // A failure inside the transaction undoes only this call. + if _, err = apply(s, tg, update("1", cv(1, str("m3"))), remove("999")); err == nil { + t.Error("missing key accepted") + } + if !s.TxState().InTransaction { + t.Error("transaction ended") + } + endTransaction(t, s, true) + setAutocommit(t, s, true) + check("m2:null,c:3,d:null") + + // An explicit transaction in autocommit mode is joined, not committed. + exec(t, s, "BEGIN TRAN", 0) + if res, err = apply(s, tg, update("1", cv(1, str("x1")))); err != nil || !res.InTransaction { + t.Errorf("joined: %+v %v", res, err) + } + exec(t, s, "ROLLBACK", 0) + check("m2:null,c:3,d:null") +} + +func TestMssqlEditRoundTrip(t *testing.T) { + s := mssqlSession(t) + exec(t, s, `DROP TABLE IF EXISTS dbo.lq_edit_types; + CREATE TABLE dbo.lq_edit_types ( + id int NOT NULL PRIMARY KEY, dec decimal(18,4), num numeric(5,2), mon money, + smon smallmoney, ti tinyint, si smallint, i int, bi bigint, fl float, re real, + b bit, d date, dt datetime, sdt smalldatetime, dt2 datetime2(7), + dto datetimeoffset(3), tm time(3), g uniqueidentifier, s nvarchar(100), + vs varchar(100), ch char(5), bin varbinary(20), fbin binary(4), x xml, + n int NULL); + INSERT INTO dbo.lq_edit_types VALUES ( + 1, 12345.6789, -0.5, 123456789.1234, -12.5, 255, -32768, -7, + 9223372036854775807, 0.1, 1.5, 1, '2024-05-21', '2024-05-21T13:45:30.997', + '2024-05-21T13:45:00', '2024-05-21T13:45:30.1234567', + '2024-05-21T13:45:30.123+05:30', '13:45:30.5', + '6f9619ff-8b86-d011-b42d-00c04fc964ff', N'it''s "q"' + CHAR(10) + N'ação', + 'plain', 'ab', 0x0A0BFF, 0x00000001, N'1', NULL)`, 0) + t.Cleanup(func() { + _, _ = run(s, "SET DATEFORMAT mdy; SET LANGUAGE us_english; DROP TABLE IF EXISTS dbo.lq_edit_types", 0) + }) + // Settings that would change implicit conversions must not matter. + exec(t, s, "SET DATEFORMAT ydm; SET LANGUAGE Deutsch", 0) + + const sel = "SELECT * FROM dbo.lq_edit_types" + before := exec(t, s, sel, 0) + tg := before.Editable + if tg == nil { + t.Fatalf("not editable: %v", before.ReadOnlyReason) + } + row := before.Rows[0] + var values []model.CellValue + for i := 1; i < len(row); i++ { + values = append(values, cv(i, row[i])) + } + res, err := apply(s, tg, model.RowChange{Op: model.OpUpdate, Key: []*string{row[0]}, Values: values}) + if err != nil { + t.Fatal(err) + } + if res.Updated != 1 { + t.Errorf("updated %d", res.Updated) + } + after := exec(t, s, sel, 0) + names := make([]string, len(before.Columns)) + for i, c := range before.Columns { + names[i] = c.Name + } + b, a := texts(before.Rows)[0], texts(after.Rows)[0] + for i, name := range names { + if a[i] != b[i] { + t.Errorf("column %s: %q became %q", name, b[i], a[i]) + } + } + + // New values typed in the displayed format. + typed := [][2]string{ + {"dt2", "2023-12-31 23:59:59.0000001"}, + {"dto", "2023-01-02 03:04:05.678 -03:00"}, + {"dt", "2023-01-13 00:00:00.003"}, + {"d", "2023-01-13"}, + {"b", "false"}, + {"bin", "0x"}, + {"dec", "-0.0001"}, + } + index := func(name string) int { + for i, n := range names { + if n == name { + return i + } + } + t.Fatalf("no column %s", name) + return -1 + } + values = nil + for _, tv := range typed { + values = append(values, cv(index(tv[0]), str(tv[1]))) + } + if _, err := apply(s, tg, update("1", values...)); err != nil { + t.Fatal(err) + } + a = texts(exec(t, s, sel, 0).Rows)[0] + for _, tv := range typed { + if got := a[index(tv[0])]; got != tv[1] { + t.Errorf("column %s: %q, want %q", tv[0], got, tv[1]) + } + } +} + +func TestMssqlEditQuotedNames(t *testing.T) { + s := mssqlSession(t) + exec(t, s, `DROP TABLE IF EXISTS dbo.[lq_edit_Mixed Case]; + CREATE TABLE dbo.[lq_edit_Mixed Case] ([Item Id] int NOT NULL PRIMARY KEY, + [Some]]Name] nvarchar(20)); + INSERT INTO dbo.[lq_edit_Mixed Case] VALUES (1, N'one');`, 0) + t.Cleanup(func() { _, _ = run(s, "DROP TABLE IF EXISTS dbo.[lq_edit_Mixed Case]", 0) }) + + tg := exec(t, s, "SELECT [Some]]Name], [Item Id] FROM dbo.[lq_edit_Mixed Case]", 0).Editable + if tg == nil || tg.Table != "lq_edit_Mixed Case" || !reflect.DeepEqual(tg.Key, []int{1}) || + tg.Columns[0] == nil || tg.Columns[0].Name != "Some]Name" { + t.Fatalf("target %+v", tg) + } + res, err := apply(s, tg, + update("1", cv(0, str("uno"))), + insert(cv(1, str("2")), cv(0, str("dos"))), + insert(cv(1, str("3"))), + remove("3")) + if err != nil { + t.Fatal(err) + } + if res.Updated != 1 || res.Deleted != 1 || res.Inserted != 2 { + t.Errorf("result %+v", res) + } + got := scalar(t, s, `SELECT STRING_AGG([Some]]Name], ',') WITHIN GROUP (ORDER BY [Item Id]) + FROM dbo.[lq_edit_Mixed Case]`) + if got != "uno,dos" { + t.Errorf("rows %q", got) + } +} + +func TestMssqlResultViewSQL(t *testing.T) { + fixtures.CheckView(t, mssqlSession(t), "sqlserver") +} + +func TestMssqlDDLSQL(t *testing.T) { + fixtures.CheckDDL(t, mssqlSession(t), "sqlserver", "dbo") +} diff --git a/internal/drivers/sqlserver/query.go b/internal/drivers/sqlserver/query.go new file mode 100644 index 0000000..abb702d --- /dev/null +++ b/internal/drivers/sqlserver/query.go @@ -0,0 +1,355 @@ +package sqlserver + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "io" + "reflect" + "strconv" + "strings" + + "github.com/golang-sql/sqlexp" + mssql "github.com/microsoft/go-mssqldb" +) + +// Reading a response +// +// Every request runs in the driver's message mode (a sqlexp.ReturnMessage +// argument), which hands the result sets over one at a time and reports +// server errors and INFO messages (PRINT, RAISERROR below severity 11) as +// messages instead of failing the request. A goroutine collects the +// messages while the result sets are read, so the driver never waits on a +// full message queue. Statement errors therefore do not stop the batch: the +// server runs the rest of it, as in SSMS, and the first error is reported +// once the whole response has been read. +// +// Closing the rows before the end of the response cancels the request with +// a TDS attention, so the response is always read to the end unless the +// call was cancelled. + +// errStopped is what onRow returning false makes query return. +var errStopped = errors.New("reading stopped") + +// msgEnd is queued after the driver's last message so the collector knows +// it has seen them all. +type msgEnd struct{} + +// messages collects what the server reports besides rows. +type messages struct { + rm *sqlexp.ReturnMessage + done chan struct{} + errs []mssql.Error + notices []string +} + +func collectMessages(rm *sqlexp.ReturnMessage) *messages { + m := &messages{rm: rm, done: make(chan struct{})} + go func() { + defer close(m.done) + for { + switch msg := rm.Message(context.Background()).(type) { + case msgEnd: + return + case sqlexp.MsgError: + var e mssql.Error + if errors.As(msg.Error, &e) { + m.errs = append(m.errs, e) + } + case sqlexp.MsgNotice: + if text, ok := notice(msg.Message); ok { + m.notices = append(m.notices, text) + } + } + } + }() + return m +} + +// finish waits until every message queued before it was collected. +func (m *messages) finish() { + _ = sqlexp.ReturnMessageEnqueue(context.Background(), m.rm, msgEnd{}) + <-m.done +} + +// notice is the text of an INFO message. Changes of database and language +// that USE and SET LANGUAGE report are left out, as SSMS does. +func notice(msg any) (string, bool) { + switch m := msg.(type) { + case mssql.Error: + if m.Number == 5701 || m.Number == 5703 { + return "", false + } + return strings.TrimRight(m.Message, " \r\n"), true + case interface{ String() string }: + return m.String(), true + } + return "", false +} + +// queryHandler receives the result sets of a response, numbered from 0. +// Returning false stops reading: the rest of the request is cancelled. +type queryHandler struct { + columns func(set int, cols []column) bool + row func(set int, values []driver.Value) bool +} + +// keepBatch makes the driver send the text as a SQL batch: a single word +// would otherwise go as a stored procedure call (go-mssqldb's isProc). +func keepBatch(sql string) string { + if strings.ContainsAny(sql, "\n\r") { + return sql + } + return sql + "\n" +} + +// query sends sql as a batch, or through sp_executesql when params are +// given (@P1, @P2...; nil is a NULL nvarchar), and reads the whole response. +// It returns the INFO messages and the first error: a transport error, the +// context's error when the request was cancelled, or the first server error. +func query(ctx context.Context, conn *mssql.Conn, text string, params []*string, h queryHandler) ([]string, error) { + if len(params) == 0 { + text = keepBatch(text) + } + st, err := conn.PrepareContext(ctx, text) + if err != nil { + return nil, err + } + stmt, ok := st.(*mssql.Stmt) + if !ok { + return nil, errors.New("unexpected statement type") + } + defer stmt.Close() + + args := make([]driver.NamedValue, len(params)) + for i, p := range params { + var v driver.Value = sql.NullString{} + if p != nil { + v = *p + } + args[i] = driver.NamedValue{Name: "P" + strconv.Itoa(i+1), Ordinal: i + 1, Value: v} + } + // Turns on message mode for this request. + rm := &sqlexp.ReturnMessage{} + if err := conn.CheckNamedValue(&driver.NamedValue{Ordinal: len(args) + 1, Value: rm}); !errors.Is(err, driver.ErrRemoveArgument) { + return nil, errors.New("the driver did not accept the message queue") + } + msgs := collectMessages(rm) + + rows, err := stmt.QueryContext(ctx, args) + if err != nil { + msgs.finish() + return msgs.notices, err + } + rq, ok := rows.(*mssql.Rowsq) + if !ok { + _ = rows.Close() + msgs.finish() + return msgs.notices, errors.New("the driver did not use message mode") + } + + fatal, stopped := readSets(ctx, rq, h) + var closeErr error + switch { + case stopped: + // Sends an attention for the rest of the request. + closeErr = rq.Close() + case fatal == nil: + // The last DONE was read; wait for the reader to end so closing + // does not cancel a finished request. + for rq.Next(nil) == nil { + } + closeErr = rq.Close() + case isServerError(fatal): + closeErr = rq.Close() + } + // After a cancel the driver has already sent the attention and read + // its acknowledgement; after a transport error the stream is lost. + if closeErr != nil && !isServerError(closeErr) && fatal == nil { + fatal = closeErr + } + msgs.finish() + + var serverErr error + if len(msgs.errs) > 0 { + serverErr = msgs.errs[0] + } + switch { + case fatal != nil && isServerError(fatal) && serverErr != nil: + return msgs.notices, serverErr + case fatal != nil: + return msgs.notices, fatal + case stopped && ctx.Err() != nil: + return msgs.notices, ctx.Err() + case stopped: + return msgs.notices, errStopped + } + return msgs.notices, serverErr +} + +// readSets reads every result set. fatal is an error that ended the +// response (transport, cancel, severe server error); stopped says the +// handler or ctx ended it early. +func readSets(ctx context.Context, rq *mssql.Rowsq, h queryHandler) (fatal error, stopped bool) { + set := -1 + for { + err := rq.NextResultSet() + if errors.Is(err, io.EOF) { + return nil, false + } + if err != nil { + return err, false + } + if !atColumns(rq) { + // The end of a statement without rows. + continue + } + set++ + cols := describe(rq) + if h.columns != nil && !h.columns(set, cols) { + return nil, true + } + dest := make([]driver.Value, len(cols)) + for { + if ctx.Err() != nil { + return nil, true + } + err := rq.Next(dest) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return err, false + } + if h.row != nil && !h.row(set, dest) { + return nil, true + } + clear(dest) + } + } +} + +// atColumns says whether NextResultSet stopped at the metadata of a result +// set rather than at the end of a statement. The driver keeps that in an +// unexported field; Columns would read ahead when it is not set. +func atColumns(rq *mssql.Rowsq) bool { + return reflect.ValueOf(rq).Elem().FieldByName("cols").Len() > 0 +} + +// describe reads the columns of the current result set. +func describe(rq *mssql.Rowsq) []column { + names := rq.Columns() + cols := make([]column, len(names)) + for i, name := range names { + cols[i] = column{name: name, dbType: dbTypeName(rq, i)} + if _, scale, ok := precisionScale(rq, i); ok { + cols[i].scale = int(scale) + } + } + return cols +} + +// dbTypeName guards against the driver's panic on types it cannot name. +func dbTypeName(rq *mssql.Rowsq, i int) (name string) { + defer func() { + if recover() != nil { + name = "" + } + }() + return rq.ColumnTypeDatabaseTypeName(i) +} + +func precisionScale(rq *mssql.Rowsq, i int) (p, s int64, ok bool) { + defer func() { + if recover() != nil { + p, s, ok = 0, 0, false + } + }() + return rq.ColumnTypePrecisionScale(i) +} + +// isServerError says whether err came from the server (the connection is +// still usable), as opposed to a transport error or a cancel. +func isServerError(err error) bool { + var e mssql.Error + return errors.As(err, &e) +} + +// isCancel says whether err is the context's: the driver sent an attention +// and the server acknowledged it. +func isCancel(err error) bool { + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + +// textRows formats rows of internal queries. +func textRow(cols []column, values []driver.Value) []*string { + out := make([]*string, len(values)) + for i, v := range values { + out[i] = formatValue(cols[i], v, binaryPreviewBytes) + } + return out +} + +// fetchAll runs sql and returns every result set as text. +func fetchAll(ctx context.Context, conn *mssql.Conn, text string, params ...*string) ([][][]*string, error) { + var sets [][][]*string + var cols []column + _, err := query(ctx, conn, text, params, queryHandler{ + columns: func(_ int, c []column) bool { + cols = c + sets = append(sets, [][]*string{}) + return true + }, + row: func(set int, values []driver.Value) bool { + sets[set] = append(sets[set], textRow(cols, values)) + return true + }, + }) + if err != nil { + return nil, err + } + return sets, nil +} + +// fetch runs sql and returns the rows of its first result set as text. +func fetch(ctx context.Context, conn *mssql.Conn, text string) ([][]*string, error) { + sets, err := fetchAll(ctx, conn, text) + if err != nil { + return nil, err + } + if len(sets) == 0 { + return nil, nil + } + return sets[0], nil +} + +// cell is the value of column i, nil when missing or NULL. +func cell(row []*string, i int) *string { + if i < len(row) { + return row[i] + } + return nil +} + +func cellText(row []*string, i int) string { + if v := cell(row, i); v != nil { + return *v + } + return "" +} + +// intAt is the integer in column i of the first row, 0 when missing. +func intAt(rows [][]*string, i int) int64 { + if len(rows) == 0 { + return 0 + } + n, _ := strconv.ParseInt(cellText(rows[0], i), 10, 64) + return n +} + +// flag reads a bit column: true or 1. +func flag(row []*string, i int) bool { + v := cellText(row, i) + return v == "true" || v == "1" +} diff --git a/internal/drivers/sqlserver/sqlserver.go b/internal/drivers/sqlserver/sqlserver.go new file mode 100644 index 0000000..d7060a3 --- /dev/null +++ b/internal/drivers/sqlserver/sqlserver.go @@ -0,0 +1,1058 @@ +// Package sqlserver is the SQL Server and Azure SQL session, over TDS with +// go-mssqldb. +// +// - Each call is sent as one SQL batch on a single connection, so +// temporary tables, USE and SET options persist across calls, as in +// SSMS. The interface splits scripts on GO. +// - Plain SELECT batches are limited by the server with SET ROWCOUNT; +// everything else stops keeping rows at the limit. +// - Manual commit uses SET IMPLICIT_TRANSACTIONS ON; @@TRANCOUNT is read +// after every call, so the transaction flag is what the server reports. +// - Cancel sends a TDS attention to the running batch (through the call's +// context). When the server does not acknowledge it, the connection is +// reopened. +// - PRINT and low-severity RAISERROR messages are returned as notices. +// rowsAffected is ROWCOUNT_BIG() of the batch's last statement. +// - Grid editing: plain queries are described by the server +// (sys.dm_exec_describe_first_result_set in browse mode) together with +// the unique keys of the source table, in one extra call. Edits are +// applied with sp_executesql and explicit, style-fixed conversions. +package sqlserver + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "io" + "net" + "net/url" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "unicode" + + mssql "github.com/microsoft/go-mssqldb" + "github.com/microsoft/go-mssqldb/integratedauth" + "github.com/microsoft/go-mssqldb/msdsn" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +// connectTimeout bounds the TCP connection and the login handshake. +const connectTimeout = 15 * time.Second + +const ( + // Login failed (bad user or password, or an account without access). + loginFailed = 18456 + // Cannot open the database requested by the login. + cannotOpenDatabase = 4060 +) + +const lostMessage = "The connection to the server was lost. Reconnect to continue." + +// sqlLogin is the integrated authentication provider that declines, so the +// driver signs in with the user and password (go-mssqldb would otherwise +// try the Windows account when the user is empty or has a domain). +const sqlLogin = "lowquery-sql-login" + +func init() { + _ = integratedauth.SetIntegratedAuthenticationProvider(sqlLogin, + integratedauth.ProviderFunc(func(msdsn.Config) (integratedauth.IntegratedAuthenticator, error) { + return nil, nil + })) +} + +// Session is one SQL Server connection. +type Session struct { + // lock serializes every call except Cancel. + lock chan struct{} + conn *mssql.Conn + live atomic.Pointer[mssql.Conn] + endpoint *endpoint + closed bool + broken atomic.Bool + + stopMu sync.Mutex + stop context.CancelFunc + + stateMu sync.Mutex + state model.TxState + + serverVersion string + currentUser *string + currentSchema *string +} + +var _ drivers.Session = (*Session)(nil) + +// Connect opens a session. password nil means none (Windows +// authentication). +func Connect(ctx context.Context, profile model.ConnectionProfile, password *string) (*Session, error) { + ep, conn, err := connectEndpoint(ctx, profile, password) + if err != nil { + return nil, err + } + rows, err := fetch(ctx, conn, + `SELECT CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(128)), + CAST(SERVERPROPERTY('EngineEdition') AS int), SUSER_SNAME(), SCHEMA_NAME()`) + if err != nil { + _ = conn.Close() + return nil, connectionError(ctx, err) + } + var row []*string + if len(rows) > 0 { + row = rows[0] + } + edition, _ := strconv.ParseInt(cellText(row, 1), 10, 64) + s := &Session{ + lock: make(chan struct{}, 1), + conn: conn, + endpoint: ep, + state: model.TxState{Autocommit: true}, + serverVersion: serverLabel(cellText(row, 0), edition), + currentUser: cell(row, 2), + currentSchema: cell(row, 3), + } + s.live.Store(conn) + return s, nil +} + +func serverLabel(version string, engineEdition int64) string { + switch engineEdition { + // 5: Azure SQL Database, 8: Azure SQL Managed Instance. + case 5, 8: + return "Azure SQL " + version + } + return "SQL Server " + version +} + +// endpoint opens connections with the settings of a profile; the session +// keeps it to reopen the connection when a cancel is not acknowledged. +type endpoint struct { + connector *mssql.Connector + dialer *handshakeDialer +} + +// connectEndpoint opens the first connection. With sslmode prefer, a server +// without encryption support is retried with only the login encrypted. +func connectEndpoint(ctx context.Context, profile model.ConnectionProfile, password *string) (*endpoint, *mssql.Conn, error) { + mode := profile.SslMode + for { + ep, err := newEndpoint(profile, password, mode) + if err != nil { + return nil, nil, err + } + conn, err := ep.open(ctx) + if err == nil { + return ep, conn, nil + } + if (mode == model.SslPrefer || mode == "") && strings.Contains(err.Error(), "server does not support encryption") { + mode = model.SslDisable + continue + } + return nil, nil, connectionError(ctx, err) + } +} + +func newEndpoint(profile model.ConnectionProfile, password *string, mode model.SslMode) (*endpoint, error) { + dsn, err := buildDSN(profile, password, mode) + if err != nil { + return nil, err + } + // A driver of our own, so the global one keeps its settings. + connector, err := (&mssql.Driver{}).OpenConnector(dsn) + if err != nil { + return nil, apperr.Invalidf("%v", err) + } + c, ok := connector.(*mssql.Connector) + if !ok { + return nil, apperr.Internalf("unexpected connector type") + } + d := &handshakeDialer{} + c.Dialer = d + return &endpoint{connector: c, dialer: d}, nil +} + +// buildDSN writes the connection URL of a profile. +func buildDSN(profile model.ConnectionProfile, password *string, mode model.SslMode) (string, error) { + host := strings.TrimSpace(profile.Host) + instance := strings.TrimSpace(profile.Instance) + port := profile.Port + if port == 0 { + port = 1433 + } + u := &url.URL{Scheme: "sqlserver"} + // With a named instance, the default port means "ask SQL Browser". + if instance != "" && (profile.Port == 0 || profile.Port == 1433) { + u.Host = host + if strings.Contains(host, ":") { + u.Host = "[" + host + "]" + } + } else { + u.Host = net.JoinHostPort(host, strconv.Itoa(int(port))) + } + if instance != "" { + u.Path = "/" + instance + } + q := url.Values{} + if profile.WindowsAuth { + if runtime.GOOS != "windows" { + return "", apperr.Invalidf("Windows authentication is only available when LowQuery runs on Windows.") + } + q.Set("authenticator", "winsspi") + } else { + pw := "" + if password != nil { + pw = *password + } + u.User = url.UserPassword(strings.TrimSpace(profile.User), pw) + q.Set("authenticator", sqlLogin) + } + if db := strings.TrimSpace(profile.Database); db != "" { + q.Set("database", db) + } + q.Set("app name", "LowQuery") + q.Set("dial timeout", strconv.Itoa(int(connectTimeout/time.Second))) + encrypt, trust := encryption(mode) + q.Set("encrypt", encrypt) + q.Set("TrustServerCertificate", trust) + u.RawQuery = q.Encode() + return u.String(), nil +} + +// encryption maps sslmode to go-mssqldb's encrypt and +// TrustServerCertificate: disable encrypts only the login packet, as SSMS +// does with Encrypt=false; prefer and require encrypt everything without +// validating the certificate; verify-full validates it. +func encryption(mode model.SslMode) (encrypt, trust string) { + switch mode { + case model.SslDisable: + return "false", "true" + case model.SslVerifyFull: + return "true", "false" + } + return "true", "true" +} + +// handshakeDialer opens TCP connections with a deadline that bounds the +// login handshake; open clears it once the login is done. +type handshakeDialer struct { + mu sync.Mutex + last net.Conn +} + +func (d *handshakeDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + nd := net.Dialer{KeepAlive: 30 * time.Second} + c, err := nd.DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + if strings.HasPrefix(network, "tcp") { + _ = c.SetDeadline(time.Now().Add(connectTimeout)) + if tc, ok := c.(*net.TCPConn); ok { + _ = tc.SetNoDelay(true) + } + d.mu.Lock() + d.last = c + d.mu.Unlock() + } + return c, nil +} + +func (d *handshakeDialer) clearDeadline() { + d.mu.Lock() + defer d.mu.Unlock() + if d.last != nil { + _ = d.last.SetDeadline(time.Time{}) + d.last = nil + } +} + +// open connects and applies the session defaults. +func (e *endpoint) open(ctx context.Context) (*mssql.Conn, error) { + dc, err := e.connector.Connect(ctx) + if err != nil { + return nil, err + } + conn, ok := dc.(*mssql.Conn) + if !ok { + _ = dc.Close() + return nil, errors.New("unexpected connection type") + } + e.dialer.clearDeadline() + if _, err := fetch(ctx, conn, "SET TEXTSIZE 2147483647; SET IMPLICIT_TRANSACTIONS OFF; SELECT 1"); err != nil { + _ = conn.Close() + return nil, err + } + return conn, nil +} + +func (s *Session) Engine() model.Engine { return model.SQLServer } +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) 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() +} + +// acquire takes the session lock and arms the context of the call, which +// Cancel or ctx stop. release clears both. +func (s *Session) acquire(ctx context.Context) (context.Context, func(), error) { + if ctx.Err() != nil { + return nil, nil, apperr.CancelledErr() + } + if s.broken.Load() { + return nil, nil, apperr.New(apperr.Connection, lostMessage) + } + select { + case s.lock <- struct{}{}: + case <-ctx.Done(): + return nil, nil, apperr.CancelledErr() + } + if s.closed { + <-s.lock + return nil, nil, apperr.New(apperr.Connection, "The connection is closed.") + } + if s.broken.Load() { + <-s.lock + return nil, nil, apperr.New(apperr.Connection, lostMessage) + } + opCtx, cancel := context.WithCancel(ctx) + s.stopMu.Lock() + s.stop = cancel + s.stopMu.Unlock() + return opCtx, func() { + s.stopMu.Lock() + s.stop = nil + s.stopMu.Unlock() + cancel() + <-s.lock + }, nil +} + +// Cancel interrupts the running call, if any: the driver sends a TDS +// attention. 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 +} + +// Close closes the connection; a running call is cancelled first. +func (s *Session) Close() error { + _ = s.Cancel(context.Background()) + select { + case s.lock <- struct{}{}: + case <-time.After(5 * time.Second): + // The call did not stop: closing the socket ends it. + if c := s.live.Load(); c != nil { + _ = c.Close() + } + s.lock <- struct{}{} + } + defer func() { <-s.lock }() + if s.closed { + return nil + } + s.closed = true + _ = s.conn.Close() + return nil +} + +// fail maps the error of a call and marks the session unusable when the +// stream broke. +func (s *Session) fail(err error, sql string, withSQL bool) *apperr.Error { + if !s.conn.IsValid() || (!isServerError(err) && !isCancel(err) && !errors.Is(err, errStopped)) { + s.broken.Store(true) + } + return mapError(err, sql, withSQL) +} + +// callErr maps the error of a call other than Execute: a cancelled call +// reports Cancelled. +func (s *Session) callErr(err error) *apperr.Error { + if isCancel(err) || errors.Is(err, errStopped) { + if !s.conn.IsValid() { + s.broken.Store(true) + } + return apperr.CancelledErr() + } + return s.fail(err, "", false) +} + +func doomed() *apperr.Error { + return apperr.New(apperr.Database, "The transaction cannot be committed (an error doomed it). Roll it back.") +} + +// batch is the first result set of a batch. +type batch struct { + columns []model.ColumnInfo + rows []model.Row + truncated bool + notices []string +} + +// readBatch runs the batch and keeps the first result set, up to maxRows +// rows. The rest of the response is read and discarded so the connection +// stays in sync. +func readBatch(ctx context.Context, conn *mssql.Conn, sql string, maxRows int) (*batch, error) { + out := &batch{} + var cols []column + limit := drivers.BinaryLimit(ctx, binaryPreviewBytes) + notices, err := query(ctx, conn, sql, nil, queryHandler{ + columns: func(set int, c []column) bool { + if set == 0 { + cols = c + out.columns = make([]model.ColumnInfo, len(c)) + for i, col := range c { + out.columns[i] = col.info() + } + out.rows = []model.Row{} + } + return true + }, + row: func(set int, values []driver.Value) bool { + if set != 0 { + return true + } + if maxRows > 0 && len(out.rows) >= maxRows { + out.truncated = true + return true + } + row := make(model.Row, len(values)) + for i, v := range values { + row[i] = formatValue(cols[i], v, limit) + } + out.rows = append(out.rows, row) + return true + }, + }) + out.notices = notices + return out, err +} + +// after is what the server reports after a batch. +type after struct { + rowcount uint64 + trancount int64 + xactState int64 + // Whether the values were read (false after a broken connection). + collected bool +} + +func parseAfter(rows [][]*string) after { + n := intAt(rows, 0) + if n < 0 { + n = 0 + } + return after{rowcount: uint64(n), trancount: intAt(rows, 1), xactState: intAt(rows, 2), collected: true} +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + + limited := req.MaxRows > 0 && rowLimitApplies(req.SQL) + text := req.SQL + if limited { + // Same line as the statement, so error line numbers do not shift. + text = fmt.Sprintf("SET ROWCOUNT %d; %s", req.MaxRows+1, req.SQL) + } + + started := time.Now() + out, runErr := readBatch(opCtx, s.conn, text, req.MaxRows) + elapsed := uint64(time.Since(started).Milliseconds()) + + var outcome *apperr.Error + if runErr != nil { + if opCtx.Err() != nil && !isServerError(runErr) { + outcome = s.cancelled(runErr) + } else { + outcome = s.fail(runErr, req.SQL, true) + } + } + + // Row count, transaction state, and the ROWCOUNT reset in one trip. The + // rest of the call is not cancellable, as the batch already ended. + var state after + if !s.broken.Load() { + sql := "SELECT ROWCOUNT_BIG(), @@TRANCOUNT, XACT_STATE();" + if limited { + sql += " SET ROWCOUNT 0;" + } + rows, err := fetch(context.Background(), s.conn, sql) + if err != nil { + e := s.fail(err, "", false) + if outcome == nil { + return nil, e + } + // Keep the original error, but say why the session broke. + if s.broken.Load() && outcome.Detail == "" { + o := *outcome + o.Detail = e.Message + return nil, &o + } + } else { + state = parseAfter(rows) + } + } + // Whether the grid may edit the rows, while the connection is held. + var target *model.EditTarget + var reason string + detected := false + if outcome == nil && out.columns != nil && state.collected { + target, reason = s.detectEdit(req.SQL, len(out.columns), state) + detected = true + } + + if state.collected { + s.setInTransaction(state.trancount > 0) + } + if outcome != nil { + return nil, outcome + } + + result := &model.ExecResult{ + Columns: out.columns, + Rows: out.rows, + Truncated: out.truncated, + ElapsedMs: elapsed, + Notices: out.notices, + InTransaction: s.TxState().InTransaction, + } + countsRows := false + if first := drivers.FirstKeywords(req.SQL, 1); len(first) > 0 { + switch first[0] { + case "INSERT", "UPDATE", "DELETE", "MERGE", "BULK": + countsRows = true + case "SELECT", "WITH": + // SELECT ... INTO and WITH ... return no result set. + countsRows = out.columns == nil + } + } + if countsRows { + n := state.rowcount + result.RowsAffected = &n + } + if state.xactState == -1 { + result.Notices = append(result.Notices, "The transaction can no longer be committed; roll it back.") + } + if detected { + if target != nil { + result.Editable = target + } else { + result.ReadOnlyReason = &reason + } + } + result.Normalize() + return result, nil +} + +// cancelled is the error of a cancelled Execute. When the server did not +// acknowledge the attention, the connection is reopened: its responses +// could no longer be matched to the requests. +func (s *Session) cancelled(runErr error) *apperr.Error { + if isCancel(runErr) && s.conn.IsValid() { + return apperr.New(apperr.Cancelled, "The statement was cancelled.") + } + if err := s.reopen(); err != nil { + s.broken.Store(true) + e := apperr.New(apperr.Cancelled, + "The statement was cancelled, but the connection could not be reopened. Reconnect to continue.") + e.Detail = apperr.From(err).Message + return e + } + e := apperr.New(apperr.Cancelled, "The statement was cancelled.") + e.Detail = "LowQuery reopened the connection to finish the cancel: temporary tables, session settings and uncommitted work of this tab were discarded." + return e +} + +// reopen replaces the connection with a new one, keeping the autocommit +// mode. +func (s *Session) reopen() error { + ctx, cancel := context.WithTimeout(context.Background(), 2*connectTimeout) + defer cancel() + fresh, err := s.endpoint.open(ctx) + if err != nil { + return connectionError(ctx, err) + } + if !s.TxState().Autocommit { + if _, err := fetch(ctx, fresh, "SET IMPLICIT_TRANSACTIONS ON; SELECT 1"); err != nil { + _ = fresh.Close() + return connectionError(ctx, err) + } + } + _ = s.conn.Close() + s.conn = fresh + s.live.Store(fresh) + s.setInTransaction(false) + return nil +} + +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return s.TxState(), err + } + defer release() + sql := "SET IMPLICIT_TRANSACTIONS ON; SELECT @@TRANCOUNT" + if on { + // Turning autocommit back on commits pending work, like JDBC. + sql = `WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; + IF @@TRANCOUNT = 0 SET IMPLICIT_TRANSACTIONS OFF; + SELECT @@TRANCOUNT` + } + rows, err := fetch(opCtx, s.conn, sql) + if err != nil { + return s.TxState(), s.callErr(err) + } + s.stateMu.Lock() + defer s.stateMu.Unlock() + s.state.InTransaction = intAt(rows, 0) > 0 + if on && s.state.InTransaction { + return s.state, doomed() + } + s.state.Autocommit = on + return s.state, nil +} + +func (s *Session) EndTransaction(ctx context.Context, commit bool) (model.TxState, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return s.TxState(), err + } + defer release() + sql := "IF @@TRANCOUNT > 0 ROLLBACK TRAN; SELECT @@TRANCOUNT" + if commit { + // Nested BEGIN TRAN needs one COMMIT per level. A doomed + // transaction cannot commit, and COMMIT would fail in a loop. + sql = "WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; SELECT @@TRANCOUNT" + } + rows, err := fetch(opCtx, s.conn, sql) + if err != nil { + return s.TxState(), s.callErr(err) + } + s.setInTransaction(intAt(rows, 0) > 0) + if s.TxState().InTransaction { + return s.TxState(), doomed() + } + return s.TxState(), nil +} + +// metadata runs a catalog query. In manual-commit mode a SELECT opens an +// implicit transaction, so one opened only by this query is ended right +// away. +func (s *Session) metadata(ctx context.Context, sql string) ([][]*string, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + if st := s.TxState(); !st.Autocommit && !st.InTransaction { + sql += ";\nIF @@TRANCOUNT > 0 COMMIT TRAN;" + } + rows, err := fetch(opCtx, s.conn, sql) + if err != nil { + return nil, s.callErr(err) + } + return rows, nil +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + // Fixed database-role schemas (db_owner...) only show up when they + // hold objects; system schemas go last. + rows, err := s.metadata(ctx, `SELECT s.name FROM sys.schemas s + WHERE s.schema_id NOT BETWEEN 16384 AND 16399 + OR EXISTS (SELECT 1 FROM sys.objects o WHERE o.schema_id = s.schema_id) + ORDER BY CASE WHEN s.name = SCHEMA_NAME() THEN 0 + WHEN s.name IN ('sys', 'INFORMATION_SCHEMA', 'guest') + OR s.schema_id BETWEEN 16384 AND 16399 THEN 2 + ELSE 1 END, s.name`) + if err != nil { + return nil, err + } + out := make([]string, 0, len(rows)) + for _, r := range rows { + if v := cell(r, 0); v != nil { + out = append(out, *v) + } + } + return out, nil +} + +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + sch := nstr(schema) + rows, err := s.metadata(ctx, `SELECT name, kind FROM ( + SELECT o.name, + CASE o.type WHEN 'U' THEN 'table' WHEN 'V' THEN 'view' + WHEN 'SO' THEN 'sequence' WHEN 'SN' THEN 'synonym' + WHEN 'P' THEN 'procedure' WHEN 'PC' THEN 'procedure' + WHEN 'X' THEN 'procedure' ELSE 'function' END AS kind + FROM sys.all_objects o + WHERE o.schema_id = SCHEMA_ID(`+sch+`) + AND o.type IN ('U','V','SO','SN','P','PC','X','FN','IF','TF','FS','FT') + AND (o.is_ms_shipped = 0 OR `+sch+` IN (N'sys', N'INFORMATION_SCHEMA')) + UNION ALL + SELECT t.name, 'type' FROM sys.types t + WHERE t.is_user_defined = 1 AND t.schema_id = SCHEMA_ID(`+sch+`) + ) x + ORDER BY kind, name`) + 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) { + rows, err := s.metadata(ctx, `SELECT c.name, `+columnType+`, + c.is_nullable, + CAST(CASE WHEN EXISTS ( + SELECT 1 FROM sys.indexes i + JOIN sys.index_columns ic ON ic.object_id = i.object_id + AND ic.index_id = i.index_id + WHERE i.object_id = c.object_id AND i.is_primary_key = 1 + AND ic.column_id = c.column_id) THEN 1 ELSE 0 END AS bit), + OBJECT_DEFINITION(c.default_object_id) + FROM sys.all_columns c + JOIN sys.types t ON t.user_type_id = c.user_type_id + WHERE c.object_id = `+objectID(schema, table)+` + ORDER BY c.column_id`) + 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) == "true", + PrimaryKey: cellText(r, 3) == "true", + DefaultValue: cell(r, 4), + } + } + return out, nil +} + +// Stream reads the first result set of a batch as the server sends it. +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + opCtx, release, err := s.acquire(ctx) + if err != nil { + return 0, err + } + defer release() + limit := drivers.BinaryLimit(drivers.WithFullValues(opCtx), binaryPreviewBytes) + send := func(ev drivers.StreamEvent) bool { + select { + case sink <- ev: + return true + case <-opCtx.Done(): + return false + } + } + var total uint64 + var cols []column + rows := make([]model.Row, 0, drivers.StreamBatch) + _, err = query(opCtx, s.conn, sql, nil, queryHandler{ + columns: func(set int, c []column) bool { + if set != 0 { + return true + } + cols = c + infos := make([]model.ColumnInfo, len(c)) + for i, col := range c { + infos[i] = col.info() + } + return send(drivers.StreamEvent{Columns: infos}) + }, + row: func(set int, values []driver.Value) bool { + if set != 0 { + return true + } + row := make(model.Row, len(values)) + for i, v := range values { + row[i] = formatValue(cols[i], v, limit) + } + rows = append(rows, row) + total++ + if len(rows) == drivers.StreamBatch { + full := rows + rows = make([]model.Row, 0, drivers.StreamBatch) + return send(drivers.StreamEvent{Rows: full}) + } + return true + }, + }) + if err != nil { + if isCancel(err) || errors.Is(err, errStopped) { + return total, s.callErr(err) + } + return total, s.fail(err, sql, true) + } + if len(rows) > 0 && !send(drivers.StreamEvent{Rows: rows}) { + return total, apperr.CancelledErr() + } + return total, nil +} + +func connectionError(ctx context.Context, err error) *apperr.Error { + if ctx.Err() != nil && !isServerError(err) { + return apperr.CancelledErr() + } + e := mapError(err, "", false) + if e.Kind != apperr.Invalid { + e.Kind = apperr.Connection + } + return e +} + +// mapError turns driver errors into the app error: server errors keep the +// SSMS-style code and the line. +func mapError(err error, sql string, withSQL bool) *apperr.Error { + var ae *apperr.Error + if errors.As(err, &ae) { + return ae + } + var e mssql.Error + if errors.As(err, &e) { + first := e + if len(e.All) > 0 { + first = e.All[0] + } + message := strings.TrimPrefix(first.Message, "login error: ") + return serverError(first.Number, first.Class, first.State, message, first.ProcName, first.LineNo, sql, withSQL) + } + if isCancel(err) { + return apperr.CancelledErr() + } + var se mssql.StreamError + if errors.As(err, &se) { + return apperr.Connectionf("Protocol error: %v", se.InnerError) + } + if closedConnection(err) { + return apperr.New(apperr.Connection, "The connection to the server was closed.") + } + return apperr.New(apperr.Connection, err.Error()) +} + +// closedConnection says whether err means the server closed the connection. +func closedConnection(err error) bool { + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, driver.ErrBadConn) || + errors.Is(err, net.ErrClosed) || errors.Is(err, syscall.ECONNRESET) || + errors.Is(err, syscall.ECONNABORTED) || errors.Is(err, syscall.EPIPE) { + return true + } + // WSAECONNABORTED and WSAECONNRESET. + var errno syscall.Errno + return errors.As(err, &errno) && (errno == 10053 || errno == 10054) +} + +// serverError builds the error with the SSMS-style code +// (Msg 208, Level 16, State 1) and the start of the reported line as +// position. +func serverError(number int32, class, state uint8, message, procedure string, line int32, sql string, withSQL bool) *apperr.Error { + e := &apperr.Error{ + Kind: apperr.Database, + Message: strings.TrimRightFunc(message, unicode.IsSpace), + Code: fmt.Sprintf("Msg %d, Level %d, State %d", number, class, state), + } + if procedure == "" { + if line > 0 { + e.Detail = fmt.Sprintf("Line %d", line) + } + if withSQL { + if pos, ok := lineStart(sql, int(line)); ok { + e.Position = &pos + } + } + } else { + e.Detail = fmt.Sprintf("Procedure %s, Line %d", procedure, line) + } + if number == loginFailed || number == cannotOpenDatabase || class >= 20 { + e.Kind = apperr.Connection + } + return e +} + +// lineStart is the 0-based character offset where the given 1-based line +// starts. +func lineStart(sql string, line int) (int, bool) { + if line <= 0 { + return 0, false + } + if line == 1 { + return 0, true + } + current := 1 + pos := 0 + for _, c := range sql { + if c == '\n' { + current++ + if current == line { + return pos + 1, true + } + } + pos++ + } + return 0, false +} + +// rowLimitApplies: SET ROWCOUNT also limits INSERT/UPDATE/DELETE and +// SELECT ... INTO, so it is only used when the batch is made of plain +// queries: it starts with SELECT (or a CTE) and no reserved word that +// writes or controls flow appears outside literals and comments. +func rowLimitApplies(sql string) bool { + first := drivers.FirstKeywords(sql, 1) + if len(first) == 0 || (first[0] != "SELECT" && first[0] != "WITH") { + return false + } + for _, w := range sqlWords(sql) { + switch w { + case "INTO", "INSERT", "UPDATE", "DELETE", "MERGE", "EXEC", "EXECUTE", "SET", "DECLARE", + "CREATE", "ALTER", "DROP", "TRUNCATE", "BEGIN", "COMMIT", "ROLLBACK", "SAVE", "USE", "IF", + "WHILE", "BULK", "DBCC", "OPEN", "CLOSE", "DEALLOCATE", "GRANT", "REVOKE", "DENY", + "BACKUP", "RESTORE": + return false + } + } + return true +} + +// sqlWords returns the uppercased words of a T-SQL text, skipping string +// literals, quoted identifiers ("x", [x]) and comments (--, nested /* */). +func sqlWords(sql string) []string { + chars := []rune(sql) + var words []string + at := func(i int) rune { + if i < len(chars) { + return chars[i] + } + return 0 + } + // closing skips to after the closing char; a doubled one is an escape. + closing := func(i int, end rune) int { + for i < len(chars) { + if chars[i] == end { + if at(i+1) == end { + i += 2 + continue + } + return i + 1 + } + i++ + } + return i + } + isWordStart := func(c rune) bool { return unicode.IsLetter(c) || c == '_' || c == '@' || c == '#' } + isWordPart := func(c rune) bool { + return unicode.IsLetter(c) || unicode.IsNumber(c) || c == '_' || c == '@' || c == '#' || c == '$' + } + i := 0 + for i < len(chars) { + c := chars[i] + switch { + case c == '\'': + i = closing(i+1, '\'') + case c == '"': + i = closing(i+1, '"') + case c == '[': + i = closing(i+1, ']') + case c == '-' && at(i+1) == '-': + for i < len(chars) && chars[i] != '\n' { + i++ + } + case c == '/' && at(i+1) == '*': + depth := 0 + for i < len(chars) { + if chars[i] == '/' && at(i+1) == '*' { + depth++ + i += 2 + } else if chars[i] == '*' && at(i+1) == '/' { + depth-- + i += 2 + if depth == 0 { + break + } + } else { + i++ + } + } + case isWordStart(c): + start := i + for i < len(chars) && isWordPart(chars[i]) { + i++ + } + word := string(chars[start:i]) + // N'...' is a Unicode literal, not the word N. + if !(strings.EqualFold(word, "N") && at(i) == '\'') { + words = append(words, strings.ToUpper(word)) + } + default: + i++ + } + } + return words +} + +// columnType is a column's type as DDL writes it, for +// sys.columns c JOIN sys.types t. +const columnType = `CASE WHEN t.is_user_defined = 1 THEN t.name + WHEN t.name IN ('varchar', 'char', 'varbinary', 'binary') + THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' + ELSE CAST(c.max_length AS varchar(10)) END + ')' + WHEN t.name IN ('nvarchar', 'nchar') + THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' + ELSE CAST(c.max_length / 2 AS varchar(10)) END + ')' + WHEN t.name IN ('decimal', 'numeric') + THEN t.name + '(' + CAST(c.precision AS varchar(10)) + ',' + + CAST(c.scale AS varchar(10)) + ')' + WHEN t.name IN ('datetime2', 'time', 'datetimeoffset') + THEN t.name + '(' + CAST(c.scale AS varchar(10)) + ')' + ELSE t.name END` + +// objectID is the OBJECT_ID of schema.name, as an expression. +func objectID(schema, name string) string { + return "OBJECT_ID(QUOTENAME(" + nstr(schema) + ") + N'.' + QUOTENAME(" + nstr(name) + "))" +} + +// nstr is a T-SQL Unicode string literal. +func nstr(s string) string { + return "N'" + strings.ReplaceAll(s, "'", "''") + "'" +} + +// quoteIdent is a bracket-quoted identifier. +func quoteIdent(name string) string { + return "[" + strings.ReplaceAll(name, "]", "]]") + "]" +} + +func qualified(schema *string, table string) string { + if schema != nil && *schema != "" { + return quoteIdent(*schema) + "." + quoteIdent(table) + } + return quoteIdent(table) +} diff --git a/internal/drivers/sqlserver/sqlserver_test.go b/internal/drivers/sqlserver/sqlserver_test.go new file mode 100644 index 0000000..ffb7c18 --- /dev/null +++ b/internal/drivers/sqlserver/sqlserver_test.go @@ -0,0 +1,292 @@ +package sqlserver + +import ( + "context" + "errors" + "fmt" + "io" + "net/url" + "reflect" + "runtime" + "testing" + "time" + + mssql "github.com/microsoft/go-mssqldb" + "github.com/microsoft/go-mssqldb/msdsn" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func str(s string) *string { return &s } + +func TestRowLimitOnlyForPlainQueries(t *testing.T) { + limited := []string{ + "select * from t", + "-- x\nWITH c AS (SELECT 1 a) SELECT * FROM c", + "SELECT 'insert into' AS x, [update] FROM t", + "SELECT N'set' FROM t /* delete */", + "SELECT * FROM t ORDER BY 1 OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", + } + for _, sql := range limited { + if !rowLimitApplies(sql) { + t.Errorf("should be limited: %s", sql) + } + } + notLimited := []string{ + "SELECT * INTO #t FROM s", + "SELECT 1 UPDATE t SET a = 1", + "WITH c AS (SELECT 1 a) DELETE FROM t WHERE a IN (SELECT a FROM c)", + "UPDATE t SET a = 1", + "EXEC sp_who", + "SELECT 1; EXEC p", + } + for _, sql := range notLimited { + if rowLimitApplies(sql) { + t.Errorf("should not be limited: %s", sql) + } + } +} + +func TestWordsSkipLiteralsAndComments(t *testing.T) { + got := sqlWords("select 'it''s' /* a /* b */ c */ [x]] y] \"q\" -- z\n from @v") + if want := []string{"SELECT", "FROM", "@V"}; !reflect.DeepEqual(got, want) { + t.Errorf("got %q", got) + } + got = sqlWords("SELECT ação, #tmp, x$1 FROM t") + if want := []string{"SELECT", "AÇÃO", "#TMP", "X$1", "FROM", "T"}; !reflect.DeepEqual(got, want) { + t.Errorf("got %q", got) + } +} + +func TestLineOffsetsAreInChars(t *testing.T) { + sql := "SELECT 'ã';\nSELECT x\nFROM t" + cases := []struct { + line int + pos int + ok bool + }{{1, 0, true}, {2, 12, true}, {3, 21, true}, {4, 0, false}, {0, 0, false}} + for _, c := range cases { + pos, ok := lineStart(sql, c.line) + if pos != c.pos || ok != c.ok { + t.Errorf("line %d: %d %v", c.line, pos, ok) + } + } +} + +func TestServerErrorsKeepCodeAndLine(t *testing.T) { + e := serverError(208, 16, 1, "Invalid object name 'x'.", "", 2, "SELECT 1;\nSELECT * FROM x", true) + if e.Code != "Msg 208, Level 16, State 1" || e.Position == nil || *e.Position != 10 || + e.Kind != apperr.Database || e.Detail != "Line 2" { + t.Errorf("%+v", e) + } + e = serverError(50000, 16, 1, "boom", "dbo.p", 7, "EXEC dbo.p", true) + if e.Position != nil || e.Detail != "Procedure dbo.p, Line 7" { + t.Errorf("%+v", e) + } + e = serverError(18456, 14, 1, "Login failed for user 'x'.", "", 1, "", false) + if e.Kind != apperr.Connection || e.Code != "Msg 18456, Level 14, State 1" { + t.Errorf("%+v", e) + } + e = serverError(4060, 11, 1, "Cannot open database.", "", 1, "", false) + if e.Kind != apperr.Connection { + t.Errorf("%+v", e) + } + e = serverError(9001, 21, 1, "log not available\n", "", 1, "", false) + if e.Kind != apperr.Connection || e.Message != "log not available" { + t.Errorf("%+v", e) + } +} + +func TestMapsDriverErrors(t *testing.T) { + // A login failure as the driver returns it. + login := mssql.Error{Number: 18456, Class: 14, State: 1, Message: "login error: Login failed for user 'sa'."} + e := mapError(fmt.Errorf("wrapped: %w", login), "", false) + if e.Code != "Msg 18456, Level 14, State 1" || e.Message != "Login failed for user 'sa'." || e.Kind != apperr.Connection { + t.Errorf("%+v", e) + } + // The first of several errors is reported, as SSMS shows it first. + all := mssql.Error{Number: 2, Class: 16, State: 1, Message: "second", LineNo: 1, + All: []mssql.Error{{Number: 1, Class: 16, State: 1, Message: "first", LineNo: 1}, {Number: 2, Class: 16, State: 1, Message: "second", LineNo: 1}}} + if e := mapError(all, "x", true); e.Message != "first" || e.Code != "Msg 1, Level 16, State 1" { + t.Errorf("%+v", e) + } + if e := mapError(io.EOF, "", false); e.Kind != apperr.Connection || e.Message != "The connection to the server was closed." { + t.Errorf("%+v", e) + } + if e := mapError(context.Canceled, "", false); e.Kind != apperr.Cancelled { + t.Errorf("%+v", e) + } + if e := mapError(mssql.StreamError{InnerError: errors.New("bad token")}, "", false); e.Kind != apperr.Connection || + e.Message != "Protocol error: bad token" { + t.Errorf("%+v", e) + } + if !isServerError(fmt.Errorf("x: %w", login)) || isServerError(io.EOF) || !isCancel(context.DeadlineExceeded) { + t.Error("error classes") + } +} + +func TestLiteralsAndLabels(t *testing.T) { + if got := nstr("o'neil"); got != "N'o''neil'" { + t.Errorf("nstr: %s", got) + } + if got := serverLabel("16.0.4135.4", 3); got != "SQL Server 16.0.4135.4" { + t.Errorf("label: %s", got) + } + if got := serverLabel("12.0.2000.8", 5); got != "Azure SQL 12.0.2000.8" { + t.Errorf("label: %s", got) + } + if got := objectID("dbo", "a'b"); got != "OBJECT_ID(QUOTENAME(N'dbo') + N'.' + QUOTENAME(N'a''b'))" { + t.Errorf("object id: %s", got) + } +} + +func TestIdentifiersAreBracketQuoted(t *testing.T) { + if got := quoteIdent("a]b"); got != "[a]]b]" { + t.Errorf("%s", got) + } + if got := qualified(str("Sales Dept"), "Order Items"); got != "[Sales Dept].[Order Items]" { + t.Errorf("%s", got) + } + if got := qualified(nil, "t"); got != "[t]" { + t.Errorf("%s", got) + } +} + +func parseDSN(t *testing.T, p model.ConnectionProfile, password *string, mode model.SslMode) msdsn.Config { + t.Helper() + dsn, err := buildDSN(p, password, mode) + if err != nil { + t.Fatal(err) + } + cfg, err := msdsn.Parse(dsn) + if err != nil { + t.Fatalf("%s: %v", dsn, err) + } + return cfg +} + +func TestConnectionSettings(t *testing.T) { + p := model.DefaultProfile() + p.Engine = model.SQLServer + p.Host = " db.example.com " + p.Port = 1433 + p.User = "sa" + p.Database = "Sales DB" + cfg := parseDSN(t, p, str("p@ss;w:rd/ü"), model.SslRequire) + if cfg.Host != "db.example.com" || cfg.Port != 1433 || cfg.Instance != "" || cfg.User != "sa" || + cfg.Password != "p@ss;w:rd/ü" || cfg.Database != "Sales DB" || cfg.AppName != "LowQuery" { + t.Errorf("%+v", cfg) + } + if cfg.Parameters["authenticator"] != sqlLogin || cfg.DialTimeout != connectTimeout { + t.Errorf("authenticator %q, dial timeout %v", cfg.Parameters["authenticator"], cfg.DialTimeout) + } + + // TLS per sslmode. + tlsCases := []struct { + mode model.SslMode + encrypt msdsn.Encryption + trust bool + }{ + {model.SslDisable, msdsn.EncryptionOff, true}, + {model.SslPrefer, msdsn.EncryptionRequired, true}, + {model.SslRequire, msdsn.EncryptionRequired, true}, + {model.SslVerifyFull, msdsn.EncryptionRequired, false}, + } + for _, c := range tlsCases { + cfg := parseDSN(t, p, str("x"), c.mode) + if cfg.Encryption != c.encrypt || cfg.TrustServerCertificate != c.trust || + cfg.TLSConfig == nil || cfg.TLSConfig.InsecureSkipVerify != c.trust { + t.Errorf("%s: encryption %v, trust %v", c.mode, cfg.Encryption, cfg.TrustServerCertificate) + } + } + + // A named instance on the default port is resolved by SQL Browser. + p.Instance = "SQLEXPRESS" + cfg = parseDSN(t, p, str("x"), model.SslPrefer) + if cfg.Host != "db.example.com" || cfg.Instance != "SQLEXPRESS" || cfg.Port != 0 { + t.Errorf("browser: %+v", cfg) + } + p.Port = 0 + if cfg = parseDSN(t, p, str("x"), model.SslPrefer); cfg.Port != 0 { + t.Errorf("browser with port 0: %d", cfg.Port) + } + // An explicit port wins. + p.Port = 50123 + if cfg = parseDSN(t, p, str("x"), model.SslPrefer); cfg.Port != 50123 || cfg.Instance != "SQLEXPRESS" { + t.Errorf("explicit port: %+v", cfg) + } + // No instance, port 0: the default port. + p.Instance = "" + p.Port = 0 + if cfg = parseDSN(t, p, str("x"), model.SslPrefer); cfg.Port != 1433 { + t.Errorf("default port: %d", cfg.Port) + } +} + +func TestWindowsAuthentication(t *testing.T) { + p := model.DefaultProfile() + p.Host = "localhost" + p.Port = 1433 + p.User = "ignored" + p.WindowsAuth = true + dsn, err := buildDSN(p, nil, model.SslPrefer) + if runtime.GOOS != "windows" { + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid { + t.Errorf("error %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(dsn) + if err != nil { + t.Fatal(err) + } + if u.User != nil || u.Query().Get("authenticator") != "winsspi" { + t.Errorf("dsn %s", dsn) + } +} + +func TestRefusedConnectionsFailFast(t *testing.T) { + p := model.DefaultProfile() + p.Engine = model.SQLServer + p.Host = "127.0.0.1" + p.Port = 1 + p.User = "x" + p.Database = "x" + started := time.Now() + s, err := Connect(context.Background(), p, 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 TestReadsDriverState(t *testing.T) { + // atColumns reads an unexported field of the driver's rows; this fails + // if a driver update renames it. + if atColumns(&mssql.Rowsq{}) { + t.Error("empty rows at columns") + } + if got := keepBatch("sp_who"); got != "sp_who\n" { + t.Errorf("%q", got) + } + if got := keepBatch("SELECT 1\nFROM t"); got != "SELECT 1\nFROM t" { + t.Errorf("%q", got) + } + if text, ok := notice(mssql.Error{Number: 0, Message: "hello"}); !ok || text != "hello" { + t.Errorf("%q %v", text, ok) + } + if _, ok := notice(mssql.Error{Number: 5701, Message: "Changed database context to 'x'."}); ok { + t.Error("database change kept") + } +} diff --git a/internal/drivers/sqlserver/values.go b/internal/drivers/sqlserver/values.go new file mode 100644 index 0000000..c87df3a --- /dev/null +++ b/internal/drivers/sqlserver/values.go @@ -0,0 +1,205 @@ +package sqlserver + +import ( + "database/sql/driver" + "fmt" + "strconv" + "strings" + "time" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// binaryPreviewBytes is how many bytes of a binary value the grid shows. +const binaryPreviewBytes = 32 * 1024 + +// previewMark marks a binary value cut by hexPreview. +const previewMark = "… (" + +// column is one result column as the driver describes it. +type column struct { + name string + // dbType is the driver's type name, uppercase (DATETIME2, MONEY...). + dbType string + // scale of time, datetime2 and datetimeoffset columns. + scale int +} + +func (c column) info() model.ColumnInfo { + return model.ColumnInfo{Name: c.name, TypeName: typeLabel(c.dbType), Kind: valueKind(c.dbType)} +} + +// typeLabel is the type name shown in the grid header, as SSMS names it. +func typeLabel(dbType string) string { + if dbType == "" { + return "null" + } + return strings.ToLower(dbType) +} + +func valueKind(dbType string) model.ValueKind { + switch dbType { + case "TINYINT", "SMALLINT", "INT", "BIGINT", "REAL", "FLOAT", "MONEY", "SMALLMONEY", "DECIMAL", "NUMERIC": + return model.KindNumber + case "BIT": + return model.KindBool + case "SMALLDATETIME", "DATETIME", "DATE", "TIME", "DATETIME2", "DATETIMEOFFSET": + return model.KindTemporal + case "VARBINARY", "BINARY", "IMAGE": + return model.KindBinary + case "VARCHAR", "CHAR", "NVARCHAR", "NCHAR", "TEXT", "NTEXT", "XML", "UNIQUEIDENTIFIER": + return model.KindText + case "", "SQL_VARIANT": + return model.KindOther + } + // CLR types (hierarchyid, geometry, geography) arrive as bytes. + return model.KindBinary +} + +// formatValue formats a value the way SSMS shows it, without losing digits. +// limit is the number of binary bytes shown (drivers.BinaryLimit). +func formatValue(c column, v driver.Value, limit int) *string { + if v == nil { + return nil + } + var s string + switch x := v.(type) { + case int64: + s = strconv.FormatInt(x, 10) + case float64: + if c.dbType == "REAL" { + s = formatFloat(strconv.FormatFloat(x, 'f', -1, 32), x) + } else { + s = formatFloat(strconv.FormatFloat(x, 'f', -1, 64), x) + } + case bool: + s = strconv.FormatBool(x) + case string: + s = x + case []byte: + switch c.dbType { + // The driver sends decimal, numeric and money values as text with + // every digit of their scale. + case "DECIMAL", "NUMERIC", "MONEY", "SMALLMONEY": + s = string(x) + case "UNIQUEIDENTIFIER": + s = guid(x) + default: + s = hexPreview(x, limit) + } + case time.Time: + s = formatTime(c, x) + default: + s = fmt.Sprint(x) + } + return &s +} + +// formatFloat keeps the shortest round-trip text and switches to the +// exponent form for very large or small values (1E+20, 1.5E-7). +func formatFloat(text string, v float64) string { + abs := v + if abs < 0 { + abs = -abs + } + if abs == 0 || (abs >= 1e-5 && abs < 1e16) { + return text + } + exp := strconv.FormatFloat(v, 'e', -1, 64) + mantissa, e, ok := strings.Cut(exp, "e") + if !ok { + return exp + } + sign := "+" + if strings.HasPrefix(e, "-") { + sign = "-" + } + digits := strings.TrimLeft(strings.TrimLeft(e, "+-"), "0") + if digits == "" { + digits = "0" + } + return mantissa + "E" + sign + digits +} + +// guid formats a uniqueidentifier from its wire bytes: the first three +// groups are little-endian. +func guid(b []byte) string { + if len(b) != 16 { + return hexPreview(b, len(b)) + } + return fmt.Sprintf("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", + b[3], b[2], b[1], b[0], b[5], b[4], b[7], b[6], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]) +} + +// hexPreview is uppercase hexadecimal with the 0x prefix, as SSMS shows +// binary values, cut after limit bytes. +func hexPreview(b []byte, limit int) string { + shown := b + if len(b) > limit { + shown = b[:limit] + } + var sb strings.Builder + sb.Grow(2 + 2*len(shown)) + sb.WriteString("0x") + const digits = "0123456789ABCDEF" + for _, c := range shown { + sb.WriteByte(digits[c>>4]) + sb.WriteByte(digits[c&0x0f]) + } + if len(b) > len(shown) { + fmt.Fprintf(&sb, "… (%d bytes)", len(b)) + } + return sb.String() +} + +func ymd(t time.Time) string { + return fmt.Sprintf("%04d-%02d-%02d", t.Year(), int(t.Month()), t.Day()) +} + +// clock is hh:mm:ss with scale fractional digits. +func clock(t time.Time, scale int) string { + s := fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second()) + if scale > 0 { + if scale > 9 { + scale = 9 + } + frac := t.Nanosecond() + for i := scale; i < 9; i++ { + frac /= 10 + } + s += fmt.Sprintf(".%0*d", scale, frac) + } + return s +} + +func formatTime(c column, t time.Time) string { + switch c.dbType { + case "DATE": + return ymd(t) + case "TIME": + return clock(t, c.scale) + case "DATETIME2": + return ymd(t) + " " + clock(t, c.scale) + case "DATETIMEOFFSET": + // The driver gives the local time of the stored offset, as SSMS + // shows it. + _, offset := t.Zone() + sign := '+' + if offset < 0 { + sign = '-' + offset = -offset + } + minutes := offset / 60 + return fmt.Sprintf("%s %s %c%02d:%02d", ymd(t), clock(t, c.scale), sign, minutes/60, minutes%60) + case "DATETIME": + // 1/300 s rounded to milliseconds (.000, .003, .007), as SSMS. + return ymd(t) + " " + clock(t, 3) + case "SMALLDATETIME": + return ymd(t) + " " + clock(t, 0) + } + // sql_variant: the scale is not known. + if t.Nanosecond() == 0 { + return ymd(t) + " " + clock(t, 0) + } + return ymd(t) + " " + clock(t, 7) +} diff --git a/internal/drivers/sqlserver/values_test.go b/internal/drivers/sqlserver/values_test.go new file mode 100644 index 0000000..273e87f --- /dev/null +++ b/internal/drivers/sqlserver/values_test.go @@ -0,0 +1,163 @@ +package sqlserver + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func show(c column, v any) string { + s := formatValue(c, v, binaryPreviewBytes) + if s == nil { + return "NULL" + } + return *s +} + +func TestFloatsUseExponentOnlyAtExtremes(t *testing.T) { + f := column{dbType: "FLOAT"} + cases := map[float64]string{ + 1.5: "1.5", + 1e20: "1E+20", + 1.5e-7: "1.5E-7", + 0: "0", + -12.5: "-12.5", + 1e15: "1000000000000000", + 0.00001: "0.00001", + -2.5e-10: "-2.5E-10", + 1e100: "1E+100", + } + for v, want := range cases { + if got := show(f, v); got != want { + t.Errorf("%v: got %q, want %q", v, got, want) + } + } + // real keeps the shortest text of the 32-bit value. + if got := show(column{dbType: "REAL"}, float64(float32(0.1))); got != "0.1" { + t.Errorf("real: %q", got) + } +} + +func TestDatesAndTimes(t *testing.T) { + utc := func(y int, m time.Month, d, h, mi, s, ns int) time.Time { + return time.Date(y, m, d, h, mi, s, ns, time.UTC) + } + cases := []struct { + col column + v time.Time + want string + }{ + {column{dbType: "DATE"}, utc(1970, 1, 1, 0, 0, 0, 0), "1970-01-01"}, + {column{dbType: "DATE"}, utc(1, 1, 1, 0, 0, 0, 0), "0001-01-01"}, + {column{dbType: "DATE"}, utc(9999, 12, 31, 0, 0, 0, 0), "9999-12-31"}, + {column{dbType: "DATE"}, utc(2023, 4, 15, 0, 0, 0, 0), "2023-04-15"}, + {column{dbType: "TIME", scale: 7}, utc(1, 1, 1, 13, 45, 30, 123456700), "13:45:30.1234567"}, + {column{dbType: "TIME", scale: 2}, utc(1, 1, 1, 13, 45, 30, 120000000), "13:45:30.12"}, + {column{dbType: "TIME", scale: 0}, utc(1, 1, 1, 13, 45, 30, 0), "13:45:30"}, + {column{dbType: "DATETIME2", scale: 3}, utc(2023, 4, 15, 0, 0, 0, 0), "2023-04-15 00:00:00.000"}, + {column{dbType: "DATETIME2", scale: 7}, utc(2024, 5, 1, 13, 45, 30, 123456700), "2024-05-01 13:45:30.1234567"}, + // datetime counts 1/300 s; the driver rounds it to milliseconds. + {column{dbType: "DATETIME"}, utc(2023, 3, 17, 13, 45, 30, 997000000), "2023-03-17 13:45:30.997"}, + {column{dbType: "DATETIME"}, utc(1900, 1, 1, 0, 0, 0, 7000000), "1900-01-01 00:00:00.007"}, + {column{dbType: "DATETIME"}, utc(1753, 1, 1, 0, 0, 0, 0), "1753-01-01 00:00:00.000"}, + {column{dbType: "SMALLDATETIME"}, utc(2023, 3, 17, 13, 45, 0, 0), "2023-03-17 13:45:00"}, + {column{dbType: "SQL_VARIANT"}, utc(2023, 3, 17, 13, 45, 0, 0), "2023-03-17 13:45:00"}, + } + for _, c := range cases { + if got := show(c.col, c.v); got != c.want { + t.Errorf("%s: got %q, want %q", c.col.dbType, got, c.want) + } + } +} + +// offsetTime builds a datetimeoffset the way the driver decodes it: the UTC +// wall time shifted by the offset, in a zone of that offset. +func offsetTime(utc time.Time, minutes int) time.Time { + return time.Date(utc.Year(), utc.Month(), utc.Day(), utc.Hour(), utc.Minute()+minutes, utc.Second(), + utc.Nanosecond(), time.FixedZone("", minutes*60)) +} + +func TestDatetimeOffsetShowsLocalTime(t *testing.T) { + col := column{dbType: "DATETIMEOFFSET", scale: 3} + utc := time.Date(2023, 4, 15, 22, 30, 0, 123000000, time.UTC) + cases := map[int]string{ + -180: "2023-04-15 19:30:00.123 -03:00", + 180: "2023-04-16 01:30:00.123 +03:00", + 330: "2023-04-16 04:00:00.123 +05:30", + 0: "2023-04-15 22:30:00.123 +00:00", + } + for offset, want := range cases { + if got := show(col, offsetTime(utc, offset)); got != want { + t.Errorf("%d: got %q, want %q", offset, got, want) + } + } +} + +func TestCellsByType(t *testing.T) { + g := []byte{0xFF, 0x19, 0x96, 0x6F, 0x86, 0x8B, 0x11, 0xD0, 0xB4, 0x2D, 0x00, 0xC0, 0x4F, 0xC9, 0x64, 0xFF} + cases := []struct { + col column + v any + want string + }{ + {column{dbType: "BIT"}, true, "true"}, + {column{dbType: "BIT"}, false, "false"}, + {column{dbType: "MONEY"}, []byte("-12.5000"), "-12.5000"}, + {column{dbType: "DECIMAL"}, []byte("1234567890123456789012345678.9012345678"), "1234567890123456789012345678.9012345678"}, + {column{dbType: "FLOAT"}, -12.5, "-12.5"}, + {column{dbType: "VARBINARY"}, []byte{0x0a, 0xff}, "0x0AFF"}, + {column{dbType: "VARBINARY"}, []byte{}, "0x"}, + {column{dbType: "UNIQUEIDENTIFIER"}, g, "6F9619FF-8B86-D011-B42D-00C04FC964FF"}, + {column{dbType: "BIGINT"}, int64(9223372036854775807), "9223372036854775807"}, + {column{dbType: "NVARCHAR"}, "ação", "ação"}, + {column{dbType: "INT"}, nil, "NULL"}, + } + for _, c := range cases { + if got := show(c.col, c.v); got != c.want { + t.Errorf("%s %v: got %q, want %q", c.col.dbType, c.v, got, c.want) + } + } +} + +func TestBinaryPreviewAndFullValues(t *testing.T) { + data := make([]byte, binaryPreviewBytes+10) + col := column{dbType: "VARBINARY"} + preview := *formatValue(col, data, drivers.BinaryLimit(context.Background(), binaryPreviewBytes)) + if !strings.HasSuffix(preview, "… (32778 bytes)") || len(preview) != 2+2*binaryPreviewBytes+len("… (32778 bytes)") { + t.Errorf("preview: %d characters, ends %q", len(preview), preview[len(preview)-20:]) + } + full := *formatValue(col, data, drivers.BinaryLimit(drivers.WithFullValues(context.Background()), binaryPreviewBytes)) + if len(full) != 2+2*len(data) || strings.Contains(full, "…") { + t.Errorf("full value: %d characters", len(full)) + } +} + +func TestColumnLabelsAndKinds(t *testing.T) { + cases := []struct { + dbType string + label string + kind model.ValueKind + }{ + {"DECIMAL", "decimal", model.KindNumber}, + {"MONEY", "money", model.KindNumber}, + {"BIT", "bit", model.KindBool}, + {"DATETIME2", "datetime2", model.KindTemporal}, + {"DATETIMEOFFSET", "datetimeoffset", model.KindTemporal}, + {"VARBINARY", "varbinary", model.KindBinary}, + {"UNIQUEIDENTIFIER", "uniqueidentifier", model.KindText}, + {"XML", "xml", model.KindText}, + {"SQL_VARIANT", "sql_variant", model.KindOther}, + {"HIERARCHYID", "hierarchyid", model.KindBinary}, + {"", "null", model.KindOther}, + } + for _, c := range cases { + info := column{name: "x", dbType: c.dbType}.info() + if info.TypeName != c.label || info.Kind != c.kind { + t.Errorf("%s: %+v", c.dbType, info) + } + } +}