From b8a1f834c24074c2a7f8675fd5cfb445d17e332d Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Sat, 13 Jan 2024 15:25:20 +0800 Subject: [PATCH 01/23] Revert "allow FromField Text and friends to accept more field types" This reverts commit 016f02bb88a5b06482b3246b3a2ec02ba13cf0e4. --- Database/SQLite/Simple/FromField.hs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Database/SQLite/Simple/FromField.hs b/Database/SQLite/Simple/FromField.hs index 35240d2..b249c81 100644 --- a/Database/SQLite/Simple/FromField.hs +++ b/Database/SQLite/Simple/FromField.hs @@ -1,4 +1,3 @@ - {-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-} {-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} @@ -159,17 +158,16 @@ instance FromField Bool where fromField f = returnError ConversionFailed f "expecting an SQLInteger column type" instance FromField T.Text where - fromField f@(Field sqlData _) = case sqlData of - SQLText v -> Ok v - SQLInteger v -> Ok $ T.pack $ show v - SQLFloat v -> Ok $ T.pack $ show v - _ -> returnError ConversionFailed f "need convertible to text" + fromField (Field (SQLText txt) _) = Ok txt + fromField f = returnError ConversionFailed f "need a text" instance FromField LT.Text where - fromField f = LT.fromStrict <$> fromField f + fromField (Field (SQLText txt) _) = Ok . LT.fromStrict $ txt + fromField f = returnError ConversionFailed f "need a text" instance FromField [Char] where - fromField f = T.unpack <$> fromField f + fromField (Field (SQLText t) _) = Ok $ T.unpack t + fromField f = returnError ConversionFailed f "expecting SQLText column type" instance FromField ByteString where fromField (Field (SQLBlob blb) _) = Ok blb From c9cf4c885ec757a4c2f72832bb923ad873c52835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Hr=C4=8Dek?= Date: Sun, 14 Jan 2024 11:02:29 +0100 Subject: [PATCH 02/23] Replace .travis.yml with autogenerated github actions config --- .github/workflows/haskell-ci.yml | 240 +++++++++++++++++++++++++++++++ .travis.yml | 3 - README.markdown | 2 +- sqlite-simple.cabal | 4 +- 4 files changed, 243 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/haskell-ci.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml new file mode 100644 index 0000000..0953646 --- /dev/null +++ b/.github/workflows/haskell-ci.yml @@ -0,0 +1,240 @@ +# This GitHub workflow config has been generated by a script via +# +# haskell-ci 'github' 'sqlite-simple.cabal' +# +# To regenerate the script (for example after adjusting tested-with) run +# +# haskell-ci regenerate +# +# For more information, see https://github.com/haskell-CI/haskell-ci +# +# version: 0.17.20231219 +# +# REGENDATA ("0.17.20231219",["github","sqlite-simple.cabal"]) +# +name: Haskell-CI +on: + - push + - pull_request +jobs: + linux: + name: Haskell-CI - Linux - ${{ matrix.compiler }} + runs-on: ubuntu-20.04 + timeout-minutes: + 60 + container: + image: buildpack-deps:bionic + continue-on-error: ${{ matrix.allow-failure }} + strategy: + matrix: + include: + - compiler: ghc-9.8.1 + compilerKind: ghc + compilerVersion: 9.8.1 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.6.3 + compilerKind: ghc + compilerVersion: 9.6.3 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.4.8 + compilerKind: ghc + compilerVersion: 9.4.8 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.2.8 + compilerKind: ghc + compilerVersion: 9.2.8 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.0.2 + compilerKind: ghc + compilerVersion: 9.0.2 + setup-method: ghcup + allow-failure: false + - compiler: ghc-8.10.7 + compilerKind: ghc + compilerVersion: 8.10.7 + setup-method: ghcup + allow-failure: false + - compiler: ghc-8.8.4 + compilerKind: ghc + compilerVersion: 8.8.4 + setup-method: hvr-ppa + allow-failure: false + fail-fast: false + steps: + - name: apt + run: | + apt-get update + apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 + if [ "${{ matrix.setup-method }}" = ghcup ]; then + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + else + apt-add-repository -y 'ppa:hvr/ghc' + apt-get update + apt-get install -y "$HCNAME" + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + fi + env: + HCKIND: ${{ matrix.compilerKind }} + HCNAME: ${{ matrix.compiler }} + HCVER: ${{ matrix.compilerVersion }} + - name: Set PATH and environment variables + run: | + echo "$HOME/.cabal/bin" >> $GITHUB_PATH + echo "LANG=C.UTF-8" >> "$GITHUB_ENV" + echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" + echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" + HCDIR=/opt/$HCKIND/$HCVER + if [ "${{ matrix.setup-method }}" = ghcup ]; then + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" + else + HC=$HCDIR/bin/$HCKIND + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" + echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" + fi + + HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') + echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" + echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" + echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" + echo "HEADHACKAGE=false" >> "$GITHUB_ENV" + echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" + echo "GHCJSARITH=0" >> "$GITHUB_ENV" + env: + HCKIND: ${{ matrix.compilerKind }} + HCNAME: ${{ matrix.compiler }} + HCVER: ${{ matrix.compilerVersion }} + - name: env + run: | + env + - name: write cabal config + run: | + mkdir -p $CABAL_DIR + cat >> $CABAL_CONFIG <> $CABAL_CONFIG < cabal-plan.xz + echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - + xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan + rm -f cabal-plan.xz + chmod a+x $HOME/.cabal/bin/cabal-plan + cabal-plan --version + - name: checkout + uses: actions/checkout@v3 + with: + path: source + - name: initial cabal.project for sdist + run: | + touch cabal.project + echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project + cat cabal.project + - name: sdist + run: | + mkdir -p sdist + $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist + - name: unpack + run: | + mkdir -p unpacked + find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; + - name: generate cabal.project + run: | + PKGDIR_sqlite_simple="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/sqlite-simple-[0-9.]*')" + echo "PKGDIR_sqlite_simple=${PKGDIR_sqlite_simple}" >> "$GITHUB_ENV" + rm -f cabal.project cabal.project.local + touch cabal.project + touch cabal.project.local + echo "packages: ${PKGDIR_sqlite_simple}" >> cabal.project + echo "package sqlite-simple" >> cabal.project + echo " ghc-options: -Werror=missing-methods" >> cabal.project + cat >> cabal.project <> cabal.project.local + cat cabal.project + cat cabal.project.local + - name: dump install plan + run: | + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all + cabal-plan + - name: restore cache + uses: actions/cache/restore@v3 + with: + key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} + path: ~/.cabal/store + restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- + - name: install dependencies + run: | + $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all + - name: build w/o tests + run: | + $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all + - name: build + run: | + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always + - name: tests + run: | + $CABAL v2-test $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --test-show-details=direct + - name: cabal check + run: | + cd ${PKGDIR_sqlite_simple} || false + ${CABAL} -vnormal check + - name: haddock + run: | + $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all + - name: unconstrained build + run: | + rm -f cabal.project.local + $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all + - name: save cache + uses: actions/cache/save@v3 + if: always() + with: + key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} + path: ~/.cabal/store diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index ec5670b..0000000 --- a/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: haskell -script: - - cabal configure --enable-tests && cabal build && cabal test diff --git a/README.markdown b/README.markdown index 3ab4e20..3bcb4a2 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,7 @@ sqlite-simple: mid-level bindings to the sqlite database ======================================================== -[![Build Status](https://secure.travis-ci.org/nurpax/sqlite-simple.png)](http://travis-ci.org/nurpax/sqlite-simple) +[![Build Status](https://github.com/nurpax/sqlite-simple/actions/workflows/main.yml/badge.svg)](https://github.com/nurpax/sqlite-simple/actions/workflows/main.yml) This library is a mid-level Haskell binding to the SQLite database. diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index 30ea3a3..4cfc7b5 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -23,7 +23,7 @@ Category: Database Build-type: Simple Cabal-version: >= 1.10 - +tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.3 || == 9.8.1 extra-source-files: README.markdown changelog @@ -57,7 +57,7 @@ Library time, transformers, Only >= 0.1 && < 0.1.1 - + if impl(ghc < 8.0) Build-depends: semigroups >= 0.18 && < 0.20 From 62363fa9c3d6bc8d59741e63cf9cda9471ab272c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Hr=C4=8Dek?= Date: Sun, 14 Jan 2024 11:03:01 +0100 Subject: [PATCH 03/23] Fix typos in haddock --- Database/SQLite/Simple.hs | 4 ++-- Database/SQLite/Simple/Ok.hs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Database/SQLite/Simple.hs b/Database/SQLite/Simple.hs index 6e3a509..1355cae 100644 --- a/Database/SQLite/Simple.hs +++ b/Database/SQLite/Simple.hs @@ -244,7 +244,7 @@ bindNamed (Statement stmt) params = do reset :: Statement -> IO () reset (Statement stmt) = Base.reset stmt --- | Return the name of a a particular column in the result set of a +-- | Return the name of a particular column in the result set of a -- 'Statement'. Throws an 'ArrayException' if the colum index is out -- of bounds. -- @@ -806,7 +806,7 @@ getQuery stmt = -- -- Although SQL can accommodate @NULL@ as a value for any of these -- types, Haskell cannot. If your result contains columns that may be --- @NULL@, be sure that you use 'Maybe' in those positions of of your +-- @NULL@, be sure that you use 'Maybe' in those positions of your -- tuple. -- -- > (Text, Maybe Int, Int) diff --git a/Database/SQLite/Simple/Ok.hs b/Database/SQLite/Simple/Ok.hs index 753acd5..819c360 100644 --- a/Database/SQLite/Simple/Ok.hs +++ b/Database/SQLite/Simple/Ok.hs @@ -19,7 +19,7 @@ -- commonly-used type and typeclass included in @base@. -- -- Extending the failure case to a list of 'SomeException's enables a --- more sensible 'Alternative' instance definitions: '<|>' concatinates +-- more sensible 'Alternative' instance definitions: '<|>' concatenates -- the list of exceptions when both cases fail, and 'empty' is defined as -- 'Errors []'. Though '<|>' one could pick one of two exceptions, and -- throw away the other, and have 'empty' provide a generic exception, From 6c1fe5e343eaa01aad86f73a14803a741e3be871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Hr=C4=8Dek?= Date: Sun, 14 Jan 2024 11:03:50 +0100 Subject: [PATCH 04/23] Remove all unused language pragmas --- Database/SQLite/Simple/FromField.hs | 7 ++++--- Database/SQLite/Simple/FromRow.hs | 3 +-- Database/SQLite/Simple/QQ.hs | 4 ++-- Database/SQLite/Simple/ToField.hs | 3 +-- Database/SQLite/Simple/Types.hs | 2 +- test/Errors.hs | 2 +- 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Database/SQLite/Simple/FromField.hs b/Database/SQLite/Simple/FromField.hs index b249c81..501d311 100644 --- a/Database/SQLite/Simple/FromField.hs +++ b/Database/SQLite/Simple/FromField.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-} -{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} -{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE CPP #-} +{-# LANGUAGE DeriveDataTypeable #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE ScopedTypeVariables #-} ------------------------------------------------------------------------------ -- | diff --git a/Database/SQLite/Simple/FromRow.hs b/Database/SQLite/Simple/FromRow.hs index fa4fdcd..919be0a 100644 --- a/Database/SQLite/Simple/FromRow.hs +++ b/Database/SQLite/Simple/FromRow.hs @@ -1,5 +1,4 @@ -{-# LANGUAGE RecordWildCards, DefaultSignatures, FlexibleContexts, - StandaloneDeriving #-} +{-# LANGUAGE DefaultSignatures, FlexibleContexts #-} ------------------------------------------------------------------------------ -- | diff --git a/Database/SQLite/Simple/QQ.hs b/Database/SQLite/Simple/QQ.hs index 53172bc..962f397 100644 --- a/Database/SQLite/Simple/QQ.hs +++ b/Database/SQLite/Simple/QQ.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TemplateHaskellQuotes #-} ------------------------------------------------------------------------------ -- | @@ -27,7 +27,7 @@ import Language.Haskell.TH.Quote (QuasiQuoter (..)) One should consider turning on the @-XQuasiQuotes@ pragma in that module: @ -{-# LANGUAGE QuasiQuoter #-} +{-# LANGUAGE QuasiQuotes #-} myQuery = query conn [sql| SELECT diff --git a/Database/SQLite/Simple/ToField.hs b/Database/SQLite/Simple/ToField.hs index 85924e5..0ec2276 100644 --- a/Database/SQLite/Simple/ToField.hs +++ b/Database/SQLite/Simple/ToField.hs @@ -1,5 +1,4 @@ -{-# LANGUAGE DeriveDataTypeable, DeriveFunctor #-} -{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} +{-# LANGUAGE FlexibleInstances #-} ------------------------------------------------------------------------------ -- | diff --git a/Database/SQLite/Simple/Types.hs b/Database/SQLite/Simple/Types.hs index 457c667..0eba8d7 100644 --- a/Database/SQLite/Simple/Types.hs +++ b/Database/SQLite/Simple/Types.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, GeneralizedNewtypeDeriving, CPP #-} +{-# LANGUAGE DeriveDataTypeable, CPP #-} ------------------------------------------------------------------------------ -- | diff --git a/test/Errors.hs b/test/Errors.hs index d1735d1..0da385e 100644 --- a/test/Errors.hs +++ b/test/Errors.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE ScopedTypeVariables, BangPatterns #-} +{-# LANGUAGE ScopedTypeVariables #-} module Errors ( testErrorsColumns From e235123af45d74d0810002d263e7cb427a793952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Hr=C4=8Dek?= Date: Sun, 14 Jan 2024 11:04:28 +0100 Subject: [PATCH 05/23] Improve Errors tests --- test/Errors.hs | 95 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 61 insertions(+), 34 deletions(-) diff --git a/test/Errors.hs b/test/Errors.hs index 0da385e..40ab7a4 100644 --- a/test/Errors.hs +++ b/test/Errors.hs @@ -23,15 +23,11 @@ import Data.Time (Day, UTCTime) import Common import Database.SQLite.Simple.Types (Null) --- The "length (show e) `seq` .." trickery below is to force evaluate --- the contents of error messages. Another option would be to log --- them (would be useful), but I don't know if HUnit has any logging --- mechanisms. Just printing them as is will look like the tests are --- hitting errors and would be confusing. -assertResultErrorCaught :: IO a -> Assertion -assertResultErrorCaught action = do - catch (action >> return False) (\(e :: ResultError) -> length (show e) `seq` return True) >>= - assertBool "assertResultError exc" +assertResultErrorThrown :: IO a -> ResultError -> Assertion +assertResultErrorThrown action expectedError = + catch + (action >> assertFailure ("Expected error: " ++ show expectedError ++ ", but nothing was thrown")) + (\(e :: ResultError) -> assertEqual "assertResultErrorThrown" expectedError e) assertFormatErrorCaught :: IO a -> Assertion assertFormatErrorCaught action = do @@ -56,54 +52,85 @@ testErrorsColumns TestEnv{..} = TestCase $ do assertEqual "row count" 1 (length rows) assertEqual "string" (Only "test string") (head rows) -- Mismatched number of output columns (selects two, dest type has 1 field) - assertResultErrorCaught (query_ conn "SELECT id,t FROM cols" :: IO [Only Int]) + assertResultErrorThrown (query_ conn "SELECT id,t FROM cols" :: IO [Only Int]) + ConversionFailed + { errSQLType = "2 values: [(\"INTEGER\",\"SQLInteger 1\"),(\"TEXT\",\"SQLText \\\"test s[...]\")]" + , errHaskellType = "at least 1 slots in target type" + , errMessage = "mismatch between number of columns to convert and number in target type" + } -- Same as above but the other way round (select 1, dst has two) - assertResultErrorCaught (query_ conn "SELECT id FROM cols" :: IO [(Int, String)]) - -- Mismatching types (source int,text doesn't match dst string,int - assertResultErrorCaught (query_ conn "SELECT id, t FROM cols" :: IO [(String, Int)]) - -- Mismatching types (source string doesn't match dst integer - assertResultErrorCaught (query_ conn "SELECT 'foo'" :: IO [Only Integer]) + assertResultErrorThrown (query_ conn "SELECT id FROM cols" :: IO [(Int, String)]) + ConversionFailed + { errSQLType = "1 values: [(\"INTEGER\",\"SQLInteger 1\")]" + , errHaskellType = "at least 2 slots in target type" + , errMessage = "mismatch between number of columns to convert and number in target type" + } + -- Mismatching types (source int,text doesn't match dst string,int) + assertResultErrorThrown (query_ conn "SELECT id, t FROM cols" :: IO [(String, Int)]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "[Char]", errMessage = "expecting SQLText column type"} + -- Mismatching types (source string doesn't match dst integer) + assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only Integer]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "Integer", errMessage = "need an int"} -- Mismatching types (sources don't match destination float/double type) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only Double]) - assertResultErrorCaught (query_ conn "SELECT 'foo'" :: IO [Only Double]) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only Float]) - assertResultErrorCaught (query_ conn "SELECT 'foo'" :: IO [Only Float]) + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only Double]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Double", errMessage = "expecting an SQLFloat column type"} + assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only Double]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "Double", errMessage = "expecting an SQLFloat column type"} + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only Float]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Float", errMessage = "expecting an SQLFloat column type"} + assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only Float]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "Float", errMessage = "expecting an SQLFloat column type"} -- Mismatching types (sources don't match destination bool type, or is out of bounds) - assertResultErrorCaught (query_ conn "SELECT 'true'" :: IO [Only Bool]) - assertResultErrorCaught (query_ conn "SELECT 2" :: IO [Only Bool]) + assertResultErrorThrown (query_ conn "SELECT 'true'" :: IO [Only Bool]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "Bool", errMessage = "expecting an SQLInteger column type"} + assertResultErrorThrown (query_ conn "SELECT 2" :: IO [Only Bool]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Bool", errMessage = "bool must be 0 or 1, got 2"} -- Mismatching types (sources don't match destination string types (text, string) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only T.Text]) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only LT.Text]) - assertResultErrorCaught (query_ conn "SELECT 1.0" :: IO [Only T.Text]) - assertResultErrorCaught (query_ conn "SELECT 1.0" :: IO [Only LT.Text]) + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only T.Text]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Text", errMessage = "need a text"} + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only LT.Text]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Text", errMessage = "need a text"} + assertResultErrorThrown (query_ conn "SELECT 1.0" :: IO [Only T.Text]) + ConversionFailed {errSQLType = "FLOAT", errHaskellType = "Text", errMessage = "need a text"} + assertResultErrorThrown (query_ conn "SELECT 1.0" :: IO [Only LT.Text]) + ConversionFailed {errSQLType = "FLOAT", errHaskellType = "Text", errMessage = "need a text"} -- Mismatching types (sources don't match destination string types (time/date) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only UTCTime]) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only Day]) + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only UTCTime]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "UTCTime", errMessage = "expecting SQLText column type"} + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only Day]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Day", errMessage = "expecting SQLText column type"} -- Mismatching types (sources don't match destination bytestring) [Only (_ :: B.ByteString)] <- query_ conn "SELECT X'3177'" - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only B.ByteString]) - assertResultErrorCaught (query_ conn "SELECT 1" :: IO [Only LB.ByteString]) - assertResultErrorCaught (query_ conn "SELECT 'foo'" :: IO [Only B.ByteString]) - assertResultErrorCaught (query_ conn "SELECT 'foo'" :: IO [Only LB.ByteString]) + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only B.ByteString]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "ByteString", errMessage = "expecting SQLBlob column type"} + assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only LB.ByteString]) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "ByteString", errMessage = "expecting SQLBlob column type"} + assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only B.ByteString]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "ByteString", errMessage = "expecting SQLBlob column type"} + assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only LB.ByteString]) + ConversionFailed {errSQLType = "TEXT", errHaskellType = "ByteString", errMessage = "expecting SQLBlob column type"} -- Trying to get a blob into a string let d = B.pack ([0..127] :: [Word8]) execute_ conn "CREATE TABLE cols_blobs (id INTEGER, b BLOB)" execute conn "INSERT INTO cols_blobs (id, b) VALUES (?,?)" (1 :: Int, d) - assertResultErrorCaught + assertResultErrorThrown (do [Only _t1] <- query conn "SELECT b FROM cols_blobs WHERE id = ?" (Only (1 :: Int)) :: IO [Only String] return ()) + ConversionFailed {errSQLType = "BLOB", errHaskellType = "[Char]", errMessage = "expecting SQLText column type"} execute_ conn "CREATE TABLE cols_bools (id INTEGER PRIMARY KEY, b BOOLEAN)" -- 3 = invalid value for bool, must be 0 or 1 execute_ conn "INSERT INTO cols_bools (b) VALUES (3)" - assertResultErrorCaught + assertResultErrorThrown (do [Only _t1] <- query_ conn "SELECT b FROM cols_bools" :: IO [Only Bool] return ()) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Bool", errMessage = "bool must be 0 or 1, got 3"} [Only (nullVal :: Null)] <- query_ conn "SELECT NULL" False @=? nullVal == nullVal False @=? nullVal /= nullVal - assertResultErrorCaught + assertResultErrorThrown (do [Only (_t1 :: Null)] <- query_ conn "SELECT 1" :: IO [Only Null] return ()) + ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Null", errMessage = "data is not null"} testErrorsInvalidParams :: TestEnv -> Test testErrorsInvalidParams TestEnv{..} = TestCase $ do From 9b51753bd3a0bb5303fb8b323dcebe4e696fbfcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Hr=C4=8Dek?= Date: Sun, 14 Jan 2024 11:04:43 +0100 Subject: [PATCH 06/23] Fix few hlint warnings --- test/Simple.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Simple.hs b/test/Simple.hs index 78abaa8..c0c530d 100644 --- a/test/Simple.hs +++ b/test/Simple.hs @@ -174,7 +174,7 @@ testSimpleUTCTime TestEnv{..} = TestCase $ do [d] <- query conn "SELECT ?" (Only (T.append zulu "Z")) matchDates (zulu, d) where - matchDates (str,(Only date)) = do + matchDates (str, Only date) = do -- Remove 'T' when reading in to Haskell let t = read (makeReadable str) :: UTCTime t @=? date @@ -198,9 +198,9 @@ testSimpleUTCTimeTZ TestEnv{..} = TestCase $ do execute_ conn "CREATE TABLE utctimestz (t TIMESTAMP)" mapM_ (\t -> execute conn "INSERT INTO utctimestz (t) VALUES (?)" (Only t)) timestrs dates <- query_ conn "SELECT t from utctimestz" :: IO [Only UTCTime] - mapM_ matchDates (zip (timestrs) dates) + mapM_ matchDates (zip timestrs dates) where - matchDates (str,(Only date)) = do + matchDates (str, Only date) = do -- Remove 'T' when reading in to Haskell let t = read . T.unpack $ str :: UTCTime t @=? date @@ -221,7 +221,7 @@ testSimpleUTCTimeParams TestEnv{..} = TestCase $ do assertEqual "UTCTime" tstr t testSimpleQueryCov :: TestEnv -> Test -testSimpleQueryCov TestEnv{..} = TestCase $ do +testSimpleQueryCov _ = TestCase $ do let str = "SELECT 1+1" :: T.Text q = "SELECT 1+1" :: Query fromQuery q @=? str From a2d4bbf99eea14595efbef8c5fa3b3e315652052 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Sun, 14 Jan 2024 19:29:14 +0800 Subject: [PATCH 07/23] Updated stack YAML files --- stack-9.2.8.yaml | 1 + stack-9.4.8.yaml | 1 + stack.yaml | 10 +--------- 3 files changed, 3 insertions(+), 9 deletions(-) create mode 100644 stack-9.2.8.yaml create mode 100644 stack-9.4.8.yaml diff --git a/stack-9.2.8.yaml b/stack-9.2.8.yaml new file mode 100644 index 0000000..352fbaa --- /dev/null +++ b/stack-9.2.8.yaml @@ -0,0 +1 @@ +resolver: lts-20.26 # 9.2.8 - base-4.16 diff --git a/stack-9.4.8.yaml b/stack-9.4.8.yaml new file mode 100644 index 0000000..18d5506 --- /dev/null +++ b/stack-9.4.8.yaml @@ -0,0 +1 @@ +resolver: lts-21.25 # 9.4.8 - base-4.17 diff --git a/stack.yaml b/stack.yaml index f527822..5b87710 100644 --- a/stack.yaml +++ b/stack.yaml @@ -1,9 +1 @@ -resolver: lts-15.1 # 8.8.2 - base-4.13 -# resolver: lts-14.27 # 8.6.5 - base-4.12 -# resolver: lts-12.26 # 8.4.4 - base-4.11 -# resolver: lts-11.22 # 8.2.2 - base-4.10 -# resolver: lts-9.21 # 8.0.2 - base-4.9 -# resolver: lts-6.35 # 7.10.3 - base-4.8 - -extra-deps: - - direct-sqlite-2.3.26 +resolver: lts-22.5 # 9.6.3 - base-4.18 From 71379f4a1761fcc95cf4934ac2e44cfdc10b04a9 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Sun, 14 Jan 2024 20:47:55 +0800 Subject: [PATCH 08/23] Updated .gitignore --- .gitignore | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 5ce26b9..b618340 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,4 @@ -cabal-dev/ -dist/ -TAGS -/*.hs.html -/hpc_*.html -/test.tix -.stack-work/ +/dist-newstyle/ +/.stack-work/ +/stack.yaml.lock +/stack-*.yaml.lock From 80be05ff2ed3c2e1cd3f6dd4561b96c94b0ba119 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Sun, 14 Jan 2024 21:11:46 +0800 Subject: [PATCH 09/23] Updated README.markdown for correct GitHub Actions links --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 3bcb4a2..aedcb53 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,7 @@ sqlite-simple: mid-level bindings to the sqlite database ======================================================== -[![Build Status](https://github.com/nurpax/sqlite-simple/actions/workflows/main.yml/badge.svg)](https://github.com/nurpax/sqlite-simple/actions/workflows/main.yml) +[![Build Status](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml/badge.svg)](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml) This library is a mid-level Haskell binding to the SQLite database. From 8da89948ec2a556ff8cc7f81f11fde4b3e10a848 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 23 Jan 2024 13:43:59 +0800 Subject: [PATCH 10/23] Updated README for Hackage badge and list of maintainers --- README.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index aedcb53..28ab6c5 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,7 @@ sqlite-simple: mid-level bindings to the sqlite database ======================================================== -[![Build Status](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml/badge.svg)](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml) +[![Build Status](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml/badge.svg)](https://github.com/nurpax/sqlite-simple/actions/workflows/haskell-ci.yml) [![Hackage](https://img.shields.io/hackage/v/sqlite-simple.svg)](https://hackage.haskell.org/package/sqlite-simple) This library is a mid-level Haskell binding to the SQLite database. @@ -95,7 +95,8 @@ tests for any such features. ## Credits - [Janne Hellsten](https://github.com/nurpax) author, long-term maintainer -- [Sergey Bushnyak](https://github.com/sigrlami) current maintainer +- [Sergey Bushnyak](https://github.com/sigrlami) long-term maintainer +- [Joshua Chia](https://github.com/jchia) current maintainer A lot of the code is directly borrowed from [mysql-simple](http://github.com/bos/mysql-simple) by Bryan O'Sullivan From e529b2ff6cc4f8d5acf42f9d28cfb13f416d8414 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 23 Jan 2024 13:56:15 +0800 Subject: [PATCH 11/23] Bumped version to 0.4.19.0 --- sqlite-simple.cabal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index 4cfc7b5..8de94e4 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -1,5 +1,5 @@ Name: sqlite-simple -Version: 0.4.18.1 +Version: 0.4.19.0 Synopsis: Mid-Level SQLite client library Description: Mid-level SQLite client library, based on postgresql-simple. From c6f91b608e40ee52bb51585abf51952fabac2b4d Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 23 Jan 2024 14:10:52 +0800 Subject: [PATCH 12/23] Renamed README.markdown to README.md --- README.markdown => README.md | 0 sqlite-simple.cabal | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename README.markdown => README.md (100%) diff --git a/README.markdown b/README.md similarity index 100% rename from README.markdown rename to README.md diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index 8de94e4..dd35d1d 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -24,7 +24,7 @@ Build-type: Simple Cabal-version: >= 1.10 tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.3 || == 9.8.1 -extra-source-files: README.markdown +extra-source-files: README.md changelog Library From fd9355d8ee5a7f44cb847adef5c476e1029d19f0 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Sat, 27 Jan 2024 01:55:16 +0800 Subject: [PATCH 13/23] Updated stack resolvers, Haskell CI and some .cabal details --- .github/workflows/haskell-ci.yml | 51 ++++++++++---------------------- sqlite-simple.cabal | 3 +- stack-9.0.yaml | 1 + stack-9.2.8.yaml | 1 - stack-9.2.yaml | 1 + stack-9.4.8.yaml | 1 - stack-9.4.yaml | 1 + stack-9.6.yaml | 1 + stack.yaml | 2 +- 9 files changed, 23 insertions(+), 39 deletions(-) create mode 100644 stack-9.0.yaml delete mode 100644 stack-9.2.8.yaml create mode 100644 stack-9.2.yaml delete mode 100644 stack-9.4.8.yaml create mode 100644 stack-9.4.yaml create mode 100644 stack-9.6.yaml mode change 100644 => 120000 stack.yaml diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 0953646..9b43d0e 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -23,7 +23,7 @@ jobs: timeout-minutes: 60 container: - image: buildpack-deps:bionic + image: buildpack-deps:jammy continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: @@ -33,9 +33,9 @@ jobs: compilerVersion: 9.8.1 setup-method: ghcup allow-failure: false - - compiler: ghc-9.6.3 + - compiler: ghc-9.6.4 compilerKind: ghc - compilerVersion: 9.6.3 + compilerVersion: 9.6.4 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 @@ -61,7 +61,7 @@ jobs: - compiler: ghc-8.8.4 compilerKind: ghc compilerVersion: 8.8.4 - setup-method: hvr-ppa + setup-method: ghcup allow-failure: false fail-fast: false steps: @@ -69,21 +69,11 @@ jobs: run: | apt-get update apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 - if [ "${{ matrix.setup-method }}" = ghcup ]; then - mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" - chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) - else - apt-add-repository -y 'ppa:hvr/ghc' - apt-get update - apt-get install -y "$HCNAME" - mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" - chmod a+x "$HOME/.ghcup/bin/ghcup" - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) - fi + mkdir -p "$HOME/.ghcup/bin" + curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + chmod a+x "$HOME/.ghcup/bin/ghcup" + "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) + "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} @@ -95,22 +85,13 @@ jobs: echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" HCDIR=/opt/$HCKIND/$HCVER - if [ "${{ matrix.setup-method }}" = ghcup ]; then - HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") - HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') - HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" - echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" - else - HC=$HCDIR/bin/$HCKIND - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV" - echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" - fi - + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" + echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index dd35d1d..a861377 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -16,6 +16,7 @@ Maintainer: Janne Hellsten Copyright: (c) 2011 MailRank, Inc., (c) 2011-2012 Leon P Smith, (c) 2012-2014 Janne Hellsten + (c) 2022-2024 Joshua Chia Homepage: http://github.com/nurpax/sqlite-simple bug-reports: http://github.com/nurpax/sqlite-simple/issues Stability: stable @@ -23,7 +24,7 @@ Category: Database Build-type: Simple Cabal-version: >= 1.10 -tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.3 || == 9.8.1 +tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.4 || == 9.8.1 extra-source-files: README.md changelog diff --git a/stack-9.0.yaml b/stack-9.0.yaml new file mode 100644 index 0000000..f9994e6 --- /dev/null +++ b/stack-9.0.yaml @@ -0,0 +1 @@ +resolver: lts-19.33 diff --git a/stack-9.2.8.yaml b/stack-9.2.8.yaml deleted file mode 100644 index 352fbaa..0000000 --- a/stack-9.2.8.yaml +++ /dev/null @@ -1 +0,0 @@ -resolver: lts-20.26 # 9.2.8 - base-4.16 diff --git a/stack-9.2.yaml b/stack-9.2.yaml new file mode 100644 index 0000000..fc9172f --- /dev/null +++ b/stack-9.2.yaml @@ -0,0 +1 @@ +resolver: lts-20.26 diff --git a/stack-9.4.8.yaml b/stack-9.4.8.yaml deleted file mode 100644 index 18d5506..0000000 --- a/stack-9.4.8.yaml +++ /dev/null @@ -1 +0,0 @@ -resolver: lts-21.25 # 9.4.8 - base-4.17 diff --git a/stack-9.4.yaml b/stack-9.4.yaml new file mode 100644 index 0000000..377040a --- /dev/null +++ b/stack-9.4.yaml @@ -0,0 +1 @@ +resolver: lts-21.25 diff --git a/stack-9.6.yaml b/stack-9.6.yaml new file mode 100644 index 0000000..cc5cf2b --- /dev/null +++ b/stack-9.6.yaml @@ -0,0 +1 @@ +resolver: lts-22.7 diff --git a/stack.yaml b/stack.yaml deleted file mode 100644 index 5b87710..0000000 --- a/stack.yaml +++ /dev/null @@ -1 +0,0 @@ -resolver: lts-22.5 # 9.6.3 - base-4.18 diff --git a/stack.yaml b/stack.yaml new file mode 120000 index 0000000..33be736 --- /dev/null +++ b/stack.yaml @@ -0,0 +1 @@ +stack-9.6.yaml \ No newline at end of file From 467e34af98e56f0a6ec69600e657a0d92500ce26 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Mon, 4 Mar 2024 00:27:00 +0800 Subject: [PATCH 14/23] Updated changelog --- changelog | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/changelog b/changelog index 6fa04ce..412a09e 100644 --- a/changelog +++ b/changelog @@ -1,5 +1,14 @@ -0.4.18.1 - * Add generic implementation of 'FromRow' and 'ToRow'. +0.4.19.0 + * Generic derivation of `FromRow` and `ToRow` + * Add `withSavePoint` + * Add `MonadFail` instance of `Ok` + +0.4.18.0 + * Allow semigroups-0.19 + * Support GHC 8.8.1 + +0.4.17.0 + * Add `createFunction` and `deleteFunction` 0.4.16.0 * Add FromField instance for SQLData (thanks @LindaOrtega, @Shimuuar) From 1a21d8de1159ed06b18ef9ca7dc6c98b6e5f5bc2 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Mon, 4 Mar 2024 00:41:21 +0800 Subject: [PATCH 15/23] Updated tested-with and haskell-ci.yml --- .github/workflows/haskell-ci.yml | 10 +++++----- sqlite-simple.cabal | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 9b43d0e..2159033 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,6 +1,6 @@ # This GitHub workflow config has been generated by a script via # -# haskell-ci 'github' 'sqlite-simple.cabal' +# haskell-ci '--distribution' 'jammy' 'github' 'sqlite-simple.cabal' # # To regenerate the script (for example after adjusting tested-with) run # @@ -8,9 +8,9 @@ # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.17.20231219 +# version: 0.18.1 # -# REGENDATA ("0.17.20231219",["github","sqlite-simple.cabal"]) +# REGENDATA ("0.18.1",["--distribution","jammy","github","sqlite-simple.cabal"]) # name: Haskell-CI on: @@ -28,9 +28,9 @@ jobs: strategy: matrix: include: - - compiler: ghc-9.8.1 + - compiler: ghc-9.8.2 compilerKind: ghc - compilerVersion: 9.8.1 + compilerVersion: 9.8.2 setup-method: ghcup allow-failure: false - compiler: ghc-9.6.4 diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index a861377..850e6ba 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -24,7 +24,7 @@ Category: Database Build-type: Simple Cabal-version: >= 1.10 -tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.4 || == 9.8.1 +tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.4 || == 9.8.2 extra-source-files: README.md changelog From 5c3558e82f8def66a5597007cd180505acfbed14 Mon Sep 17 00:00:00 2001 From: Alexey Khudyakov Date: Sat, 2 Apr 2022 19:46:01 +0300 Subject: [PATCH 16/23] Fix MonadThrow instance Since Ok can store any exception in makes no reason to erase type of exception and convert it to ErrorCall This also makes MonadThrow instance not conditional on existence of MonadFail instances --- Database/SQLite/Simple/Ok.hs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Database/SQLite/Simple/Ok.hs b/Database/SQLite/Simple/Ok.hs index 819c360..80433f5 100644 --- a/Database/SQLite/Simple/Ok.hs +++ b/Database/SQLite/Simple/Ok.hs @@ -81,10 +81,11 @@ instance Monad Ok where #if MIN_VERSION_base(4,9,0) instance MonadFail Ok where fail str = Errors [SomeException (ErrorCall str)] +#endif instance MonadThrow Ok where - throwM = fail . show -#endif + throwM = Errors . pure . toException + -- | a way to reify a list of exceptions into a single exception From 7c58a229def9f81a9c1de9f372dc188642f554f1 Mon Sep 17 00:00:00 2001 From: Ryan Hendrickson Date: Mon, 24 Feb 2025 16:37:25 -0500 Subject: [PATCH 17/23] Remove noncanonical definitions This appeases the -Wnoncanonical-monad-instances warning. This warning exists because a future GHC release may treat noncanonical definitions as errors. See also: https://gitlab.haskell.org/ghc/ghc/-/wikis/proposal/monad-of-no-return --- Database/SQLite/Simple/Ok.hs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Database/SQLite/Simple/Ok.hs b/Database/SQLite/Simple/Ok.hs index 80433f5..15fe39a 100644 --- a/Database/SQLite/Simple/Ok.hs +++ b/Database/SQLite/Simple/Ok.hs @@ -73,8 +73,6 @@ instance MonadPlus Ok where mplus = (<|>) instance Monad Ok where - return = Ok - Errors es >>= _ = Errors es Ok a >>= f = f a From f9cd5d0f5e6696ac771bb452c66ad8589fcb9dc8 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Fri, 6 Mar 2026 15:40:44 +0800 Subject: [PATCH 18/23] Updated stack resolvers, Haskell CI and some .cabal details --- .github/workflows/haskell-ci.yml | 67 +++++++++++++++++--------------- sqlite-simple.cabal | 4 +- stack-9.10.yaml | 1 + stack-9.6.yaml | 2 +- stack-9.8.yaml | 1 + stack.yaml | 2 +- 6 files changed, 42 insertions(+), 35 deletions(-) create mode 100644 stack-9.10.yaml create mode 100644 stack-9.8.yaml diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml index 2159033..a2b5e3b 100644 --- a/.github/workflows/haskell-ci.yml +++ b/.github/workflows/haskell-ci.yml @@ -1,6 +1,6 @@ # This GitHub workflow config has been generated by a script via # -# haskell-ci '--distribution' 'jammy' 'github' 'sqlite-simple.cabal' +# haskell-ci '--distribution' 'noble' 'github' 'sqlite-simple.cabal' # # To regenerate the script (for example after adjusting tested-with) run # @@ -8,9 +8,9 @@ # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.18.1 +# version: 0.19.20250506 # -# REGENDATA ("0.18.1",["--distribution","jammy","github","sqlite-simple.cabal"]) +# REGENDATA ("0.19.20250506",["--distribution","noble","github","sqlite-simple.cabal"]) # name: Haskell-CI on: @@ -19,23 +19,28 @@ on: jobs: linux: name: Haskell-CI - Linux - ${{ matrix.compiler }} - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 timeout-minutes: 60 container: - image: buildpack-deps:jammy + image: buildpack-deps:noble continue-on-error: ${{ matrix.allow-failure }} strategy: matrix: include: - - compiler: ghc-9.8.2 + - compiler: ghc-9.10.3 compilerKind: ghc - compilerVersion: 9.8.2 + compilerVersion: 9.10.3 setup-method: ghcup allow-failure: false - - compiler: ghc-9.6.4 + - compiler: ghc-9.8.4 compilerKind: ghc - compilerVersion: 9.6.4 + compilerVersion: 9.8.4 + setup-method: ghcup + allow-failure: false + - compiler: ghc-9.6.7 + compilerKind: ghc + compilerVersion: 9.6.7 setup-method: ghcup allow-failure: false - compiler: ghc-9.4.8 @@ -58,22 +63,31 @@ jobs: compilerVersion: 8.10.7 setup-method: ghcup allow-failure: false - - compiler: ghc-8.8.4 - compilerKind: ghc - compilerVersion: 8.8.4 - setup-method: ghcup - allow-failure: false fail-fast: false steps: - - name: apt + - name: apt-get install run: | apt-get update - apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 + apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo6 + - name: Install GHCup + run: | mkdir -p "$HOME/.ghcup/bin" - curl -sL https://downloads.haskell.org/ghcup/0.1.20.0/x86_64-linux-ghcup-0.1.20.0 > "$HOME/.ghcup/bin/ghcup" + curl -sL https://downloads.haskell.org/ghcup/0.1.50.1/x86_64-linux-ghcup-0.1.50.1 > "$HOME/.ghcup/bin/ghcup" chmod a+x "$HOME/.ghcup/bin/ghcup" + - name: Install cabal-install + run: | + "$HOME/.ghcup/bin/ghcup" install cabal 3.14.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + echo "CABAL=$HOME/.ghcup/bin/cabal-3.14.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" + - name: Install GHC (GHCup) + if: matrix.setup-method == 'ghcup' + run: | "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) - "$HOME/.ghcup/bin/ghcup" install cabal 3.10.2.0 || (cat "$HOME"/.ghcup/logs/*.* && false) + HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") + HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') + HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') + echo "HC=$HC" >> "$GITHUB_ENV" + echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" + echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} @@ -84,21 +98,12 @@ jobs: echo "LANG=C.UTF-8" >> "$GITHUB_ENV" echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" - HCDIR=/opt/$HCKIND/$HCVER - HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER") - HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#') - HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#') - echo "HC=$HC" >> "$GITHUB_ENV" - echo "HCPKG=$HCPKG" >> "$GITHUB_ENV" - echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV" - echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.2.0 -vnormal+nowrap" >> "$GITHUB_ENV" HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" echo "HEADHACKAGE=false" >> "$GITHUB_ENV" echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" - echo "GHCJSARITH=0" >> "$GITHUB_ENV" env: HCKIND: ${{ matrix.compilerKind }} HCNAME: ${{ matrix.compiler }} @@ -148,7 +153,7 @@ jobs: chmod a+x $HOME/.cabal/bin/cabal-plan cabal-plan --version - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: path: source - name: initial cabal.project for sdist @@ -176,7 +181,7 @@ jobs: echo " ghc-options: -Werror=missing-methods" >> cabal.project cat >> cabal.project <> cabal.project.local + $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(sqlite-simple)$/; }' >> cabal.project.local cat cabal.project cat cabal.project.local - name: dump install plan @@ -184,7 +189,7 @@ jobs: $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all cabal-plan - name: restore cache - uses: actions/cache/restore@v3 + uses: actions/cache/restore@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store @@ -214,8 +219,8 @@ jobs: rm -f cabal.project.local $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all - name: save cache - uses: actions/cache/save@v3 if: always() + uses: actions/cache/save@v4 with: key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} path: ~/.cabal/store diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index 850e6ba..7a0f373 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -16,7 +16,7 @@ Maintainer: Janne Hellsten Copyright: (c) 2011 MailRank, Inc., (c) 2011-2012 Leon P Smith, (c) 2012-2014 Janne Hellsten - (c) 2022-2024 Joshua Chia + (c) 2022-2026 Joshua Chia Homepage: http://github.com/nurpax/sqlite-simple bug-reports: http://github.com/nurpax/sqlite-simple/issues Stability: stable @@ -24,7 +24,7 @@ Category: Database Build-type: Simple Cabal-version: >= 1.10 -tested-with: GHC == 8.8.4 || == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.4 || == 9.8.2 +tested-with: GHC == 8.10.7 || == 9.0.2 || == 9.2.8 || == 9.4.8 || == 9.6.7 || == 9.8.4 || == 9.10.3 extra-source-files: README.md changelog diff --git a/stack-9.10.yaml b/stack-9.10.yaml new file mode 100644 index 0000000..753e117 --- /dev/null +++ b/stack-9.10.yaml @@ -0,0 +1 @@ +resolver: lts-24.33 diff --git a/stack-9.6.yaml b/stack-9.6.yaml index cc5cf2b..1fe2deb 100644 --- a/stack-9.6.yaml +++ b/stack-9.6.yaml @@ -1 +1 @@ -resolver: lts-22.7 +resolver: lts-22.44 diff --git a/stack-9.8.yaml b/stack-9.8.yaml new file mode 100644 index 0000000..e54b316 --- /dev/null +++ b/stack-9.8.yaml @@ -0,0 +1 @@ +resolver: lts-23.28 diff --git a/stack.yaml b/stack.yaml index 33be736..3610612 120000 --- a/stack.yaml +++ b/stack.yaml @@ -1 +1 @@ -stack-9.6.yaml \ No newline at end of file +stack-9.10.yaml \ No newline at end of file From 1887e1e38944691607f3632c918b9ebc9e656dee Mon Sep 17 00:00:00 2001 From: Adam Sandberg Ericsson Date: Tue, 6 Oct 2020 19:51:31 +0100 Subject: [PATCH 19/23] improve error message for `FromField UTCTime` and `FromField Day` --- Database/SQLite/Simple/FromField.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Database/SQLite/Simple/FromField.hs b/Database/SQLite/Simple/FromField.hs index 501d311..5ade933 100644 --- a/Database/SQLite/Simple/FromField.hs +++ b/Database/SQLite/Simple/FromField.hs @@ -182,7 +182,7 @@ instance FromField UTCTime where fromField f@(Field (SQLText t) _) = case parseUTCTime t of Right t -> Ok t - Left e -> returnError ConversionFailed f ("couldn't parse UTCTime field: " ++ e) + Left e -> returnError ConversionFailed f ("couldn't parse UTCTime field: " ++ e ++ ", field contents: " ++ T.unpack t) fromField f = returnError ConversionFailed f "expecting SQLText column type" @@ -191,7 +191,7 @@ instance FromField Day where fromField f@(Field (SQLText t) _) = case parseDay t of Right t -> Ok t - Left e -> returnError ConversionFailed f ("couldn't parse Day field: " ++ e) + Left e -> returnError ConversionFailed f ("couldn't parse Day field: " ++ e ++ ", field contents: " ++ T.unpack t) fromField f = returnError ConversionFailed f "expecting SQLText column type" From 749c1f26fa0391266488ffdbcee142343c50f0a7 Mon Sep 17 00:00:00 2001 From: Tristan McLeay Date: Wed, 18 Mar 2026 08:41:57 +1100 Subject: [PATCH 20/23] Add queryNamedWith and foldNamedWith (#115) Added queryNamedWith, foldWith, foldWith_, and foldNamedWith --------- Co-authored-by: Tristan Mc Leay --- Database/SQLite/Simple.hs | 53 +++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/Database/SQLite/Simple.hs b/Database/SQLite/Simple.hs index 1355cae..298f064 100644 --- a/Database/SQLite/Simple.hs +++ b/Database/SQLite/Simple.hs @@ -67,13 +67,17 @@ module Database.SQLite.Simple ( , queryWith , queryWith_ , queryNamed + , queryNamedWith , lastInsertRowId , changes , totalChanges -- * Queries that stream results , fold + , foldWith , fold_ + , foldWith_ , foldNamed + , foldNamedWith -- * Statements that do not return results , execute , execute_ @@ -379,8 +383,12 @@ queryWith_ fromRow_ conn query = -- r \<- 'queryNamed' c \"SELECT * FROM posts WHERE id=:id AND date>=:date\" [\":id\" ':=' postId, \":date\" ':=' afterDate] -- @ queryNamed :: (FromRow r) => Connection -> Query -> [NamedParam] -> IO [r] -queryNamed conn templ params = - withStatementNamedParams conn templ params $ \stmt -> doFoldToList fromRow stmt +queryNamed = queryNamedWith fromRow + +-- | A version of 'queryNamed' that takes an explicit 'RowParser'. +queryNamedWith :: RowParser r -> Connection -> Query -> [NamedParam] -> IO [r] +queryNamedWith fromRow_ conn templ params = + withStatementNamedParams conn templ params $ \stmt -> doFoldToList fromRow_ stmt -- | A version of 'execute' that does not perform query substitution. execute_ :: Connection -> Query -> IO () @@ -414,9 +422,19 @@ fold :: ( FromRow row, ToRow params ) -> a -> (a -> row -> IO a) -> IO a -fold conn query params initalState action = +fold = foldWith fromRow + +foldWith :: ( ToRow params ) + => RowParser row + -> Connection + -> Query + -> params + -> a + -> (a -> row -> IO a) + -> IO a +foldWith fromRow_ conn query params initalState action = withStatementParams conn query params $ \stmt -> - doFold fromRow stmt initalState action + doFold fromRow_ stmt initalState action -- | A version of 'fold' which does not perform parameter substitution. fold_ :: ( FromRow row ) @@ -425,9 +443,18 @@ fold_ :: ( FromRow row ) -> a -> (a -> row -> IO a) -> IO a -fold_ conn query initalState action = +fold_ = foldWith_ fromRow + +-- | A version of 'fold_' that takes an explicit 'RowParser'. +foldWith_ :: RowParser row + -> Connection + -> Query + -> a + -> (a -> row -> IO a) + -> IO a +foldWith_ fromRow_ conn query initalState action = withStatement conn query $ \stmt -> - doFold fromRow stmt initalState action + doFold fromRow_ stmt initalState action -- | A version of 'fold' where the query parameters (placeholders) are -- named. @@ -438,9 +465,19 @@ foldNamed :: ( FromRow row ) -> a -> (a -> row -> IO a) -> IO a -foldNamed conn query params initalState action = +foldNamed = foldNamedWith fromRow + +-- | A version of 'foldNamed' that takes an explicit 'RowParser'. +foldNamedWith :: RowParser row + -> Connection + -> Query + -> [NamedParam] + -> a + -> (a -> row -> IO a) + -> IO a +foldNamedWith fromRow_ conn query params initalState action = withStatementNamedParams conn query params $ \stmt -> - doFold fromRow stmt initalState action + doFold fromRow_ stmt initalState action doFold :: RowParser row -> Statement -> a -> (a -> row -> IO a) -> IO a doFold fromRow_ stmt initState action = From 6f83e16f1bba40c8b9a726c713434f580741da6d Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 17 Mar 2026 02:06:47 +0800 Subject: [PATCH 21/23] Reordered execute, query and fold functions and updated their documentation --- Database/SQLite/Simple.hs | 153 +++++++++++++++++++------------------- 1 file changed, 78 insertions(+), 75 deletions(-) diff --git a/Database/SQLite/Simple.hs b/Database/SQLite/Simple.hs index 298f064..536726a 100644 --- a/Database/SQLite/Simple.hs +++ b/Database/SQLite/Simple.hs @@ -64,25 +64,25 @@ module Database.SQLite.Simple ( -- * Queries that return results , query , query_ + , queryNamed , queryWith , queryWith_ - , queryNamed , queryNamedWith , lastInsertRowId , changes , totalChanges -- * Queries that stream results , fold - , foldWith , fold_ - , foldWith_ , foldNamed + , foldWith + , foldWith_ , foldNamedWith -- * Statements that do not return results , execute - , execute_ , executeMany , executeNamed + , execute_ , field -- * Transactions , withTransaction @@ -318,27 +318,6 @@ withStatementNamedParams :: Connection withStatementNamedParams conn template namedParams action = withStatement conn template $ \stmt -> bindNamed stmt namedParams >> action stmt --- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not --- expected to return results. --- --- Throws 'FormatError' if the query could not be formatted correctly. -execute :: (ToRow q) => Connection -> Query -> q -> IO () -execute conn template qs = - withStatementParams conn template qs $ \(Statement stmt) -> - void . Base.step $ stmt - --- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not --- expected to return results. --- --- Throws 'FormatError' if the query could not be formatted correctly. -executeMany :: ToRow q => Connection -> Query -> [q] -> IO () -executeMany conn template paramRows = withStatement conn template $ \stmt -> do - let Statement stmt' = stmt - forM_ paramRows $ \params -> - withBind stmt params - (void . Base.step $ stmt') - - doFoldToList :: RowParser row -> Statement -> IO [row] doFoldToList fromRow_ stmt = fmap reverse $ doFold fromRow_ stmt [] (\acc e -> return (e : acc)) @@ -363,19 +342,8 @@ query = queryWith fromRow query_ :: (FromRow r) => Connection -> Query -> IO [r] query_ = queryWith_ fromRow --- | A version of 'query' that takes an explicit 'RowParser'. -queryWith :: (ToRow q) => RowParser r -> Connection -> Query -> q -> IO [r] -queryWith fromRow_ conn templ qs = - withStatementParams conn templ qs $ \stmt -> doFoldToList fromRow_ stmt - --- | A version of 'query' that does not perform query substitution and --- takes an explicit 'RowParser'. -queryWith_ :: RowParser r -> Connection -> Query -> IO [r] -queryWith_ fromRow_ conn query = - withStatement conn query (doFoldToList fromRow_) - --- | A version of 'query' where the query parameters (placeholders) --- are named. +-- | A version of 'query' whose query parameters (placeholders) are +-- named. -- -- Example: -- @@ -385,24 +353,23 @@ queryWith_ fromRow_ conn query = queryNamed :: (FromRow r) => Connection -> Query -> [NamedParam] -> IO [r] queryNamed = queryNamedWith fromRow --- | A version of 'queryNamed' that takes an explicit 'RowParser'. +-- | A version of 'query' that takes an explicit 'RowParser'. +queryWith :: (ToRow q) => RowParser r -> Connection -> Query -> q -> IO [r] +queryWith fromRow_ conn templ qs = + withStatementParams conn templ qs $ \stmt -> doFoldToList fromRow_ stmt + +-- | A version of 'query' that takes an explicit 'RowParser' and does +-- not perform query substitution. +queryWith_ :: RowParser r -> Connection -> Query -> IO [r] +queryWith_ fromRow_ conn query = + withStatement conn query (doFoldToList fromRow_) + +-- | A version of 'query' whose query parameters (placeholders) are +-- named that takes an explicit 'RowParser'. queryNamedWith :: RowParser r -> Connection -> Query -> [NamedParam] -> IO [r] queryNamedWith fromRow_ conn templ params = withStatementNamedParams conn templ params $ \stmt -> doFoldToList fromRow_ stmt --- | A version of 'execute' that does not perform query substitution. -execute_ :: Connection -> Query -> IO () -execute_ conn template = - withStatement conn template $ \(Statement stmt) -> - void $ Base.step stmt - --- | A version of 'execute' where the query parameters (placeholders) --- are named. -executeNamed :: Connection -> Query -> [NamedParam] -> IO () -executeNamed conn template params = - withStatementNamedParams conn template params $ \(Statement stmt) -> - void $ Base.step stmt - -- | Perform a @SELECT@ or other SQL query that is expected to return results. -- Results are converted and fed into the 'action' callback as they are being -- retrieved from the database. @@ -424,6 +391,27 @@ fold :: ( FromRow row, ToRow params ) -> IO a fold = foldWith fromRow +-- | A version of 'fold' that does not perform query substitution. +fold_ :: ( FromRow row ) + => Connection + -> Query + -> a + -> (a -> row -> IO a) + -> IO a +fold_ = foldWith_ fromRow + +-- | A version of 'fold' whose query parameters (placeholders) are +-- named. +foldNamed :: ( FromRow row ) + => Connection + -> Query + -> [NamedParam] + -> a + -> (a -> row -> IO a) + -> IO a +foldNamed = foldNamedWith fromRow + +-- | A version of 'fold' that takes an explicit 'RowParser'. foldWith :: ( ToRow params ) => RowParser row -> Connection @@ -436,16 +424,8 @@ foldWith fromRow_ conn query params initalState action = withStatementParams conn query params $ \stmt -> doFold fromRow_ stmt initalState action --- | A version of 'fold' which does not perform parameter substitution. -fold_ :: ( FromRow row ) - => Connection - -> Query - -> a - -> (a -> row -> IO a) - -> IO a -fold_ = foldWith_ fromRow - --- | A version of 'fold_' that takes an explicit 'RowParser'. +-- | A version of 'fold' that takes an explicit 'RowParser' and does +-- not perform query substitution. foldWith_ :: RowParser row -> Connection -> Query @@ -454,20 +434,10 @@ foldWith_ :: RowParser row -> IO a foldWith_ fromRow_ conn query initalState action = withStatement conn query $ \stmt -> - doFold fromRow_ stmt initalState action - --- | A version of 'fold' where the query parameters (placeholders) are --- named. -foldNamed :: ( FromRow row ) - => Connection - -> Query - -> [NamedParam] - -> a - -> (a -> row -> IO a) - -> IO a -foldNamed = foldNamedWith fromRow + doFold fromRow_ stmt initalState action --- | A version of 'foldNamed' that takes an explicit 'RowParser'. +-- | A version of 'fold' whose query parameters (placeholders) are +-- named that takes an explicit 'RowParser'. foldNamedWith :: RowParser row -> Connection -> Query @@ -491,6 +461,39 @@ doFold fromRow_ stmt initState action = val' `seq` loop val' Nothing -> return val +-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not +-- expected to return results. +-- +-- Throws 'FormatError' if the query could not be formatted correctly. +execute :: (ToRow q) => Connection -> Query -> q -> IO () +execute conn template qs = + withStatementParams conn template qs $ \(Statement stmt) -> + void . Base.step $ stmt + +-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not +-- expected to return results. +-- +-- Throws 'FormatError' if the query could not be formatted correctly. +executeMany :: ToRow q => Connection -> Query -> [q] -> IO () +executeMany conn template paramRows = withStatement conn template $ \stmt -> do + let Statement stmt' = stmt + forM_ paramRows $ \params -> + withBind stmt params + (void . Base.step $ stmt') + +-- | A version of 'execute' where the query parameters (placeholders) +-- are named. +executeNamed :: Connection -> Query -> [NamedParam] -> IO () +executeNamed conn template params = + withStatementNamedParams conn template params $ \(Statement stmt) -> + void $ Base.step stmt + +-- | A version of 'execute' that does not perform query substitution. +execute_ :: Connection -> Query -> IO () +execute_ conn template = + withStatement conn template $ \(Statement stmt) -> + void $ Base.step stmt + -- | Extracts the next row from the prepared statement. nextRow :: (FromRow r) => Statement -> IO (Maybe r) nextRow = nextRowWith fromRow From 88a6dcef029a2832e7460b7f94637c43aef2a1b5 Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 17 Mar 2026 15:29:24 +0800 Subject: [PATCH 22/23] Added returnRowError --- Database/SQLite/Simple.hs | 1 + Database/SQLite/Simple/FromRow.hs | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Database/SQLite/Simple.hs b/Database/SQLite/Simple.hs index 536726a..b12a5ae 100644 --- a/Database/SQLite/Simple.hs +++ b/Database/SQLite/Simple.hs @@ -84,6 +84,7 @@ module Database.SQLite.Simple ( , executeNamed , execute_ , field + , returnRowError -- * Transactions , withTransaction , withImmediateTransaction diff --git a/Database/SQLite/Simple/FromRow.hs b/Database/SQLite/Simple/FromRow.hs index 919be0a..57337ce 100644 --- a/Database/SQLite/Simple/FromRow.hs +++ b/Database/SQLite/Simple/FromRow.hs @@ -23,9 +23,10 @@ module Database.SQLite.Simple.FromRow , field , fieldWith , numFieldsRemaining + , returnRowError ) where -import Control.Exception (SomeException(..)) +import Control.Exception (Exception, SomeException(..)) import Control.Monad (replicateM) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Reader @@ -134,6 +135,9 @@ numFieldsRemaining = RP $ do (columnIdx,_) <- lift get return $! ncols - columnIdx +returnRowError :: Exception err => err -> RowParser a +returnRowError err = RP . lift . lift $ Errors [SomeException err] + instance (FromField a) => FromRow (Only a) where fromRow = Only <$> field From 2b7b708036ea8e9cf0446b0ab11d530db5e25e8b Mon Sep 17 00:00:00 2001 From: Joshua Chia Date: Tue, 17 Mar 2026 15:30:11 +0800 Subject: [PATCH 23/23] Added 'With' tests --- sqlite-simple.cabal | 1 + test/Main.hs | 3 +- test/With.hs | 367 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 370 insertions(+), 1 deletion(-) create mode 100644 test/With.hs diff --git a/sqlite-simple.cabal b/sqlite-simple.cabal index 7a0f373..e581d59 100644 --- a/sqlite-simple.cabal +++ b/sqlite-simple.cabal @@ -95,6 +95,7 @@ test-suite test , TestImports , UserInstances , Utf8Strings + , With ghc-options: -Wall -fno-warn-name-shadowing -fno-warn-unused-do-bind diff --git a/test/Main.hs b/test/Main.hs index ff5fcc8..5a6188b 100644 --- a/test/Main.hs +++ b/test/Main.hs @@ -17,6 +17,7 @@ import TestImports() import TestImports import UserInstances import Utf8Strings +import With tests :: [TestEnv -> Test] tests = @@ -68,7 +69,7 @@ tests = , TestLabel "Imports" . testImports , TestLabel "QQ" . testSimpleQQ , TestLabel "QQ" . testMultiLinedQQ - ] + ] ++ testsWith -- | Action for connecting to the database that will be used for testing. -- diff --git a/test/With.hs b/test/With.hs new file mode 100644 index 0000000..43a8cc3 --- /dev/null +++ b/test/With.hs @@ -0,0 +1,367 @@ +{-# LANGUAGE DerivingVia, RankNTypes, ScopedTypeVariables, TypeApplications #-} + +module With ( + testsWith + ) where + +import Control.Exception (Exception, bracket_, catch) +import Control.Monad (replicateM, when) +import Data.List (intercalate) +import Data.Semigroup (Sum(..)) +import Data.String (fromString) +import qualified Data.Text as T +import Data.Typeable (Typeable) + +import Common +import Database.SQLite.Simple.FromRow (RowParser, numFieldsRemaining) + +newtype IntWrapper = IntWrapper Int + deriving (Eq, Show) + deriving (Semigroup, Monoid) via Sum Int + +data TestRowError + = WrongArity + | TooManyNullColumns + deriving (Eq, Show, Typeable) + +instance Exception TestRowError + +data AccessMode = QueryMode | FoldMode + deriving Show + +data BindingMode = Underscore | Positional | Named + deriving Show + +data Table + = ReversePairTable + | ConcatText1Table + | ConcatText2Table + | ConcatText3Table + | ConcatText4Table + deriving (Eq, Show) + +data PathKind = Happy | Unhappy + deriving (Eq, Show) + +-- TableDef is the declarative per-table metadata. It keeps the fixture rows, +-- parser, and binding-mode-specific expected happy results in one place. +data TableDef good bad r e = TableDef + { tableDefName :: String + , tableDefColumns :: [ColumnDef] + , tableDefParser :: RowParser r + , tableDefGoodRows :: [good] + , tableDefBadRows :: [bad] + , tableDefHappyRowsUnsuffixed :: [r] + , tableDefHappyRowsSuffixed :: [r] + , tableDefError :: e + } + +data ColumnDef = ColumnDef + { columnDefName :: String + , columnDefType :: String + } + +-- TableSpec is the fully compiled form used by the test matrix: +-- setup/teardown, bad-row injection, and the final assertion. +data TableSpec = TableSpec + { withTable :: forall a. Connection -> IO a -> IO a + , injectBadRow :: Connection -> IO () + , assertFor :: AccessMode -> BindingMode -> PathKind -> Connection -> Assertion + } + +-- Cover the product of access mode, binding mode, table shape, and path kind. +-- ConcatText4Table is only meaningful on the unhappy path. +testsWith :: [TestEnv -> Test] +testsWith = + [ mkTest accessMode bindingMode table pathKind + | accessMode <- [QueryMode, FoldMode] + , bindingMode <- [Underscore, Positional, Named] + , table <- [ReversePairTable, ConcatText1Table, ConcatText2Table, ConcatText3Table, ConcatText4Table] + , pathKind <- [Happy, Unhappy] + , table /= ConcatText4Table || pathKind == Unhappy + ] + +assertExceptionThrown :: forall e a. (Eq e, Show e, Exception e) => IO a -> e -> Assertion +assertExceptionThrown action expectedError = + catch + (action >> assertFailure ("Expected error: " ++ show expectedError ++ ", but nothing was thrown")) + (\(e :: e) -> assertEqual "assertExceptionThrown" expectedError e) + +-- A 2-column parser that deliberately swaps the SQL column order. +reversePairRowParser :: RowParser (IntWrapper, T.Text) +reversePairRowParser = (\txt i -> (IntWrapper i, txt)) <$> field <*> field + +-- A row-level parser with cross-column validation. It accepts only 2-3 +-- columns, rejects rows with too many NULLs, then reverses and concatenates the +-- rendered column payloads. +concatTextRowParser :: RowParser T.Text +concatTextRowParser = do + n <- numFieldsRemaining + cols <- replicateM n (field :: RowParser SQLData) + if n /= 2 && n /= 3 then + returnRowError WrongArity + else if length (filter isNull cols) > 1 then + returnRowError TooManyNullColumns + else + return . T.concat . reverse $ map payload cols + where + isNull SQLNull = True + isNull _ = False + + payload (SQLText t) = t + payload SQLNull = T.empty + payload (SQLInteger i) = T.pack (show i) + payload (SQLFloat d) = T.pack (show d) + payload (SQLBlob b) = T.pack (show b) + +expectedTypeError :: ResultError +expectedTypeError = + ConversionFailed + { errSQLType = "NULL" + , errHaskellType = "Text" + , errMessage = "need a text" + } + +mkTest :: AccessMode -> BindingMode -> Table -> PathKind -> TestEnv -> Test +mkTest accessMode bindingMode table pathKind TestEnv{conn} = + TestLabel label . TestCase $ + withTable tableSpec conn $ do + when (pathKind == Unhappy) $ + injectBadRow tableSpec conn + assertFor tableSpec accessMode bindingMode pathKind conn + where + tableSpec = compileTable table + label = + "With/" + ++ show accessMode + ++ "/" + ++ functionLabel accessMode bindingMode + ++ "/" + ++ show table + ++ "/" + ++ show pathKind + +compileTable :: Table -> TableSpec +compileTable ReversePairTable = + compileTableDef TableDef + { tableDefName = "with_reverse_pair" + , tableDefColumns = [ColumnDef "t1" "TEXT", ColumnDef "i" "INTEGER"] + , tableDefParser = reversePairRowParser + , tableDefGoodRows = + ([ ("a", 1) + , ("b", 2) + ] :: [(T.Text, Int)]) + , tableDefBadRows = + ([(Nothing @T.Text, Just @Int 8)] :: [(Maybe T.Text, Maybe Int)]) + , tableDefHappyRowsUnsuffixed = + ([ (IntWrapper 1, "a") + , (IntWrapper 2, "b") + ] :: [(IntWrapper, T.Text)]) + , tableDefHappyRowsSuffixed = + ([ (IntWrapper 1, "az") + , (IntWrapper 2, "bz") + ] :: [(IntWrapper, T.Text)]) + , tableDefError = expectedTypeError + } +compileTable ConcatText1Table = + compileTableDef TableDef + { tableDefName = "with_concat_text1" + , tableDefColumns = [ColumnDef "t1" "TEXT", ColumnDef "i" "INTEGER"] + , tableDefParser = concatTextRowParser + , tableDefGoodRows = + ([ (Just "c", Just 3) + , (Nothing, Just 4) + , (Just "d", Nothing) + ] :: [(Maybe T.Text, Maybe Int)]) + , tableDefBadRows = + ([(Nothing, Nothing)] :: [(Maybe T.Text, Maybe Int)]) + , tableDefHappyRowsUnsuffixed = (["4", "3c", "d"] :: [T.Text]) + , tableDefHappyRowsSuffixed = (["4", "3cz", "dz"] :: [T.Text]) + , tableDefError = TooManyNullColumns + } +compileTable ConcatText2Table = + compileTableDef TableDef + { tableDefName = "with_concat_text2" + , tableDefColumns = [ColumnDef "t1" "TEXT", ColumnDef "t2" "TEXT"] + , tableDefParser = concatTextRowParser + , tableDefGoodRows = + ([ (Just "e", Just "f") + , (Nothing, Just "g") + , (Just "h", Nothing) + ] :: [(Maybe T.Text, Maybe T.Text)]) + , tableDefBadRows = + ([(Nothing, Nothing)] :: [(Maybe T.Text, Maybe T.Text)]) + , tableDefHappyRowsUnsuffixed = (["g", "fe", "h"] :: [T.Text]) + , tableDefHappyRowsSuffixed = (["g", "fez", "hz"] :: [T.Text]) + , tableDefError = TooManyNullColumns + } +compileTable ConcatText3Table = + compileTableDef TableDef + { tableDefName = "with_concat_text3" + , tableDefColumns = [ColumnDef "t1" "TEXT", ColumnDef "i" "INTEGER", ColumnDef "t2" "TEXT"] + , tableDefParser = concatTextRowParser + , tableDefGoodRows = + ([ (Just "i", Just 5, Just "j") + , (Nothing, Just 6, Just "k") + , (Just "l", Nothing, Just "m") + , (Just "n", Just 7, Nothing) + ] :: [(Maybe T.Text, Maybe Int, Maybe T.Text)]) + , tableDefBadRows = + ([(Nothing, Nothing, Just "o")] :: [(Maybe T.Text, Maybe Int, Maybe T.Text)]) + , tableDefHappyRowsUnsuffixed = (["k6", "j5i", "ml", "7n"] :: [T.Text]) + , tableDefHappyRowsSuffixed = (["k6", "j5iz", "mlz", "7nz"] :: [T.Text]) + , tableDefError = TooManyNullColumns + } +compileTable ConcatText4Table = + compileTableDef TableDef + { tableDefName = "with_concat_text4" + , tableDefColumns = + [ ColumnDef "t1" "TEXT" + , ColumnDef "t2" "TEXT" + , ColumnDef "t3" "TEXT" + , ColumnDef "t4" "TEXT" + ] + , tableDefParser = concatTextRowParser + , tableDefGoodRows = + ([("p", "q", "r", "s")] :: [(T.Text, T.Text, T.Text, T.Text)]) + , tableDefBadRows = ([] :: [(T.Text, T.Text, T.Text, T.Text)]) + , tableDefHappyRowsUnsuffixed = ([] :: [T.Text]) + , tableDefHappyRowsSuffixed = ([] :: [T.Text]) + , tableDefError = WrongArity + } + +-- Turn declarative table metadata into executable test behavior. +compileTableDef + :: (ToRow good, ToRow bad, Eq r, Show r, Monoid r, Eq e, Show e, Exception e) + => TableDef good bad r e + -> TableSpec +compileTableDef TableDef + { tableDefName + , tableDefColumns + , tableDefParser + , tableDefGoodRows + , tableDefBadRows + , tableDefHappyRowsUnsuffixed + , tableDefHappyRowsSuffixed + , tableDefError + } = + TableSpec + { withTable = \conn -> + bracket_ + (do + execute_ conn (createTableSql tableDefName tableDefColumns) + executeMany conn (insertSql tableDefName tableDefColumns) tableDefGoodRows) + (execute_ conn ("DROP TABLE " <> fromString tableDefName)) + , injectBadRow = \conn -> + executeMany conn (insertSql tableDefName tableDefColumns) tableDefBadRows + , assertFor = + mkAssertFor + tableDefParser + tableDefName + tableDefColumns + tableDefHappyRowsUnsuffixed + tableDefHappyRowsSuffixed + tableDefError + } + +-- The same table data is checked through both query-like and fold-like APIs. +-- Underscore uses the unsuffixed expectations; positional and named use the +-- suffixed expectations because they bind the same "z" suffix parameter. +mkAssertFor + :: (Eq r, Show r, Monoid r, Eq e, Show e, Exception e) + => RowParser r + -> String + -> [ColumnDef] + -> [r] + -> [r] + -> e + -> AccessMode -> BindingMode -> PathKind -> Connection -> Assertion +mkAssertFor parser tableName columns happyRowsUnsuffixed happyRowsSuffixed unhappyError accessMode bindingMode pathKind conn = + case (accessMode, pathKind) of + (QueryMode, Happy) -> do + actual <- runQuerySpec parser tableName columns bindingMode conn + expectedHappyRows @=? actual + (QueryMode, Unhappy) -> + assertExceptionThrown + (runQuerySpec parser tableName columns bindingMode conn) + unhappyError + (FoldMode, Happy) -> do + actual <- runFoldSpec parser tableName columns bindingMode conn + mconcat expectedHappyRows @=? actual + (FoldMode, Unhappy) -> + assertExceptionThrown + (runFoldSpec parser tableName columns bindingMode conn) + unhappyError + where + expectedHappyRows = + case bindingMode of + Underscore -> happyRowsUnsuffixed + Positional -> happyRowsSuffixed + Named -> happyRowsSuffixed + +-- BindingMode changes how the first selected column is formed and how the +-- suffix parameter is passed to the library call. +runQuerySpec :: RowParser r -> String -> [ColumnDef] -> BindingMode -> Connection -> IO [r] +runQuerySpec parser tableName columns bindingMode conn = + case bindingMode of + Underscore -> + queryWith_ parser conn (selectSql Underscore tableName columns) + Positional -> + queryWith parser conn (selectSql Positional tableName columns) (Only @T.Text "z") + Named -> + queryNamedWith parser conn (selectSql Named tableName columns) [":suffix" := ("z" :: T.Text)] + +runFoldSpec :: Monoid r => RowParser r -> String -> [ColumnDef] -> BindingMode -> Connection -> IO r +runFoldSpec parser tableName columns bindingMode conn = + case bindingMode of + Underscore -> + foldWith_ parser conn (selectSql Underscore tableName columns) mempty appendMonoid + Positional -> + foldWith parser conn (selectSql Positional tableName columns) (Only @T.Text "z") mempty appendMonoid + Named -> + foldNamedWith parser conn (selectSql Named tableName columns) [":suffix" := ("z" :: T.Text)] mempty appendMonoid + where + appendMonoid acc row = return (acc <> row) + +createTableSql :: String -> [ColumnDef] -> Query +createTableSql name columns = + fromString + ( "CREATE TABLE " + ++ name + ++ " (" + ++ intercalate ", " [columnDefName ++ " " ++ columnDefType | ColumnDef{columnDefName, columnDefType} <- columns] + ++ ")" + ) + +insertSql :: String -> [ColumnDef] -> Query +insertSql name columns = + fromString + ( "INSERT INTO " + ++ name + ++ " VALUES (" + ++ intercalate ", " (replicate (length columns) "?") + ++ ")" + ) + +selectSql :: BindingMode -> String -> [ColumnDef] -> Query +selectSql bindingMode tableName (firstCol:restCols) = + fromString + ( "SELECT " + ++ intercalate ", " (renderFirst bindingMode firstCol : map columnDefName restCols) + ++ " FROM " + ++ tableName + ++ " ORDER BY t1" + ) + where + renderFirst Underscore = columnDefName + renderFirst Positional = \col -> columnDefName col ++ " || ?" + renderFirst Named = \col -> columnDefName col ++ " || :suffix" +selectSql _ _ [] = error "selectSql requires at least one column" + +functionLabel :: AccessMode -> BindingMode -> String +functionLabel QueryMode Underscore = "queryWith_" +functionLabel QueryMode Positional = "queryWith" +functionLabel QueryMode Named = "queryNamedWith" +functionLabel FoldMode Underscore = "foldWith_" +functionLabel FoldMode Positional = "foldWith" +functionLabel FoldMode Named = "foldNamedWith"