3 Commits

Author SHA1 Message Date
nkanaev
348693fa95 github: set workflow trigger conditions 2025-03-12 22:48:05 +00:00
nkanaev
b40c6fc9e4 github: run build after test 2025-03-12 22:22:40 +00:00
nkanaev
73fd637b23 github: test workflow 2025-03-12 22:15:18 +00:00
89 changed files with 20656 additions and 45673 deletions

View File

@@ -1,25 +0,0 @@
name: Build & Upload
inputs:
id:
description: artifact name
required: true
cmd:
description: command to run
required: true
out:
description: path to output file
required: true
runs:
using: composite
steps:
- name: compile
run: ${{ inputs.cmd }}
shell: bash
- name: archive
run: tar -cvf ${{ inputs.out }}.tar ${{ inputs.out }}
shell: bash
- name: upload
uses: actions/upload-artifact@v4
with:
name: ${{ inputs.id }}
path: ${{ inputs.out }}.tar

View File

@@ -1,12 +1,10 @@
name: Publish Docker Image name: Publish Docker Image
on: on:
push: push:
tags: tags: [ 'v*.*.*', 'v*.*', 'v*', 'latest' ]
- v*
env: env:
REGISTRY: ghcr.io REGISTRY: ghcr.io
IMAGE_NAME: nkanaev/yarr IMAGE_NAME: nkanaev/yarr
jobs: jobs:
build-and-push-image: build-and-push-image:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -15,10 +13,10 @@ jobs:
packages: write packages: write
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Log in to the Container registry - name: Log in to the Container registry
uses: docker/login-action@v3 uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with: with:
registry: ${{ env.REGISTRY }} registry: ${{ env.REGISTRY }}
username: ${{ github.actor }} username: ${{ github.actor }}
@@ -26,16 +24,15 @@ jobs:
- name: Extract Docker metadata - name: Extract Docker metadata
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with: with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Build and push Docker image - name: Build and push Docker image
uses: docker/build-push-action@v6 uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a
with: with:
context: . context: .
file: ./etc/dockerfile file: ./etc/dockerfile
push: true push: true
tags: ${{ steps.meta.outputs.tags }} tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }} labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64,linux/arm64

View File

@@ -5,116 +5,169 @@ on:
tags: tags:
- v* - v*
workflow_dispatch: workflow_dispatch:
workflow_run:
workflows: [Test]
types:
- completed
jobs: jobs:
build_macos: build_macos:
name: Build for MacOS name: Build for MacOS
runs-on: macos-13 runs-on: macos-13
steps: steps:
- name: Checkout - name: "Checkout"
uses: actions/checkout@v4 uses: actions/checkout@v2
- name: Setup Go
uses: actions/setup-go@v4
with: with:
go-version: '^1.23' submodules: 'recursive'
- name: Build arm64 gui - name: "Setup Go"
uses: ./.github/actions/prepare uses: actions/setup-go@v2
with: with:
id: darwin_arm64_gui go-version: '^1.17'
cmd: make darwin_arm64_gui - name: Cache Go Modules
out: out/darwin_arm64_gui/yarr.app uses: actions/cache@v4
- name: Build amd64 gui
uses: ./.github/actions/prepare
with: with:
id: darwin_amd64_gui path: ~/go/pkg/mod
cmd: make darwin_amd64_gui key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
out: out/darwin_amd64_gui/yarr.app restore-keys: |
- name: Build arm64 cli ${{ runner.os }}-go-
uses: ./.github/actions/prepare - name: "Build"
run: make build_macos
- name: Upload
uses: actions/upload-artifact@v4
with: with:
id: darwin_arm64 name: macos
cmd: make darwin_arm64 path: _output/macos/yarr.app
out: out/darwin_arm64/yarr
- name: Build amd64 cli
uses: ./.github/actions/prepare
with:
id: darwin_amd64
cmd: make darwin_amd64
out: out/darwin_amd64/yarr
build_windows: build_windows:
name: Build for Windows name: Build for Windows
runs-on: windows-2022 runs-on: windows-2022
steps: steps:
- name: Checkout - name: "Checkout"
uses: actions/checkout@v4 uses: actions/checkout@v2
- name: Setup Go
uses: actions/setup-go@v4
with: with:
go-version: '^1.23' submodules: 'recursive'
- name: Build amd64 gui - name: "Setup Go"
uses: ./.github/actions/prepare uses: actions/setup-go@v2
with: with:
id: windows_amd64_gui go-version: '^1.17'
cmd: make windows_amd64_gui - name: Cache Go Modules
out: out/windows_amd64_gui/yarr.exe uses: actions/cache@v4
- name: Build arm64 gui
if: false
uses: ./.github/actions/prepare
with: with:
id: windows_arm64_gui path: ~/go/pkg/mod
cmd: make windows_arm64_gui key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
out: out/windows_arm64_gui/yarr.exe restore-keys: |
${{ runner.os }}-go-
- name: "Build"
run: make build_windows
- name: Upload
uses: actions/upload-artifact@v4
with:
name: windows
path: _output/windows/yarr.exe
build_multi_cli: build_linux:
name: Build for Windows/MacOS/Linux CLI name: Build for Linux
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- name: Checkout - name: "Checkout"
uses: actions/checkout@v4 uses: actions/checkout@v2
- name: Setup Go
uses: actions/setup-go@v4
with: with:
go-version: '^1.23' submodules: 'recursive'
- name: Setup Zig - name: "Setup Go"
uses: mlugg/setup-zig@v1 uses: actions/setup-go@v2
with: with:
version: 0.14.0 go-version: '^1.17'
- name: Build linux/amd64 - name: Cache Go Modules
uses: ./.github/actions/prepare uses: actions/cache@v4
with: with:
id: linux_amd64 path: ~/go/pkg/mod
cmd: make linux_amd64 key: ${{ runner.os }}-amd64-go-${{ hashFiles('**/go.sum') }}
out: out/linux_amd64/yarr restore-keys: |
- name: Build linux/arm64 ${{ runner.os }}-go-amd64
uses: ./.github/actions/prepare - name: "Build"
run: make build_linux
- name: Upload
uses: actions/upload-artifact@v4
with: with:
id: linux_arm64 name: linux
cmd: make linux_arm64 path: _output/linux/yarr
out: out/linux_arm64/yarr
- name: Build linux/armv7 build_linux-arm:
uses: ./.github/actions/prepare name: Build for Linux ARM
runs-on: ubuntu-22.04
steps:
- name: Install dependencies
run: >
sudo apt-get install -y
gcc-arm-linux-gnueabihf
libc6-dev-armhf-cross
- name: "Checkout"
uses: actions/checkout@v2
with: with:
id: linux_armv7 submodules: 'recursive'
cmd: make linux_armv7 - name: "Setup Go"
out: out/linux_armv7/yarr uses: actions/setup-go@v2
- name: Build windows/amd64
uses: ./.github/actions/prepare
with: with:
id: windows_amd64 go-version: '^1.17'
cmd: make windows_amd64 - name: Cache Go Modules
out: out/windows_amd64/yarr uses: actions/cache@v4
- name: Build windows/arm64
uses: ./.github/actions/prepare
with: with:
id: windows_arm64 path: ~/go/pkg/mod
cmd: make windows_arm64 key: ${{ runner.os }}-armv7-go-${{ hashFiles('**/go.sum') }}
out: out/windows_arm64/yarr restore-keys: |
${{ runner.os }}-go-armv7
- name: "Build"
env:
CC: arm-linux-gnueabihf-gcc
GOARCH: arm
GOARM: 7
run: make build_linux
- name: Upload
uses: actions/upload-artifact@v4
with:
name: linux_arm
path: _output/linux/yarr
build_linux-arm64:
name: Build for Linux ARM64
runs-on: ubuntu-22.04
steps:
- name: Install dependencies
run: >
sudo apt-get install -y
gcc-aarch64-linux-gnu
libc6-dev-arm64-cross
- name: "Checkout"
uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: "Setup Go"
uses: actions/setup-go@v2
with:
go-version: '^1.17'
- name: Cache Go Modules
uses: actions/cache@v4
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-arm64-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-arm64
- name: "Build"
env:
CC: aarch64-linux-gnu-gcc
GOARCH: arm64
run: make build_linux
- name: Upload
uses: actions/upload-artifact@v4
with:
name: linux_arm64
path: _output/linux/yarr
create_release: create_release:
name: Create Release name: Create Release
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [build_macos, build_windows, build_multi_cli] if: ${{ startsWith(github.ref, 'refs/tags/') && !contains(github.ref, 'test') }}
needs: [build_macos, build_windows, build_linux, build_linux-arm, build_linux-arm64]
steps: steps:
- name: Download Artifacts - name: Download Artifacts
uses: actions/download-artifact@v4.1.7 uses: actions/download-artifact@v4.1.7
@@ -122,16 +175,17 @@ jobs:
path: . path: .
- name: Preparation - name: Preparation
run: | run: |
set -ex
ls -R ls -R
for tarfile in `ls **/*.tar`; do chmod u+x macos/Contents/MacOS/yarr
tar -xvf $tarfile chmod u+x linux/yarr
done chmod u+x linux_arm/yarr
for dir in out/*; do chmod u+x linux_arm64/yarr
echo "Compressing: $dir"
(test -d "$dir" && cd $dir && zip -r ../yarr_`basename $dir`.zip *) mv macos yarr.app && zip -r yarr-${GITHUB_REF_NAME}-macos64.zip yarr.app
done ( cd windows && zip ../yarr-${GITHUB_REF_NAME}-windows64.zip yarr.exe )
ls out ( cd linux && zip ../yarr-${GITHUB_REF_NAME}-linux64.zip yarr )
( cd linux_arm && zip ../yarr-${GITHUB_REF_NAME}-linux_arm.zip yarr )
( cd linux_arm64 && zip ../yarr-${GITHUB_REF_NAME}-linux_arm64.zip yarr )
- name: Upload Release - name: Upload Release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
env: env:
@@ -140,4 +194,8 @@ jobs:
draft: true draft: true
prerelease: true prerelease: true
files: | files: |
out/*.zip yarr-${{ github.ref_name }}-macos64.zip
yarr-${{ github.ref_name }}-windows64.zip
yarr-${{ github.ref_name }}-linux64.zip
yarr-${{ github.ref_name }}-linux_arm.zip
yarr-${{ github.ref_name }}-linux_arm64.zip

View File

@@ -8,7 +8,7 @@ jobs:
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v4

1
.gitignore vendored
View File

@@ -1,5 +1,4 @@
/_output /_output
/out
/yarr /yarr
*.db *.db
*.db-shm *.db-shm

View File

@@ -0,0 +1,48 @@
package main
import (
"flag"
"io/ioutil"
"strings"
)
var rsrc = `1 VERSIONINFO
FILEVERSION {VERSION_COMMA},0,0
PRODUCTVERSION {VERSION_COMMA},0,0
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "080904E4"
BEGIN
VALUE "CompanyName", "Old MacDonald's Farm"
VALUE "FileDescription", "Yet another RSS reader"
VALUE "FileVersion", "{VERSION}"
VALUE "InternalName", "yarr"
VALUE "LegalCopyright", "nkanaev"
VALUE "OriginalFilename", "yarr.exe"
VALUE "ProductName", "yarr"
VALUE "ProductVersion", "{VERSION}"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x809, 1252
END
END
1 ICON "icon.ico"
`
func main() {
var version, outfile string
flag.StringVar(&version, "version", "0.0", "")
flag.StringVar(&outfile, "outfile", "versioninfo.rc", "")
flag.Parse()
version_comma := strings.ReplaceAll(version, ".", ",")
out := strings.ReplaceAll(rsrc, "{VERSION}", version)
out = strings.ReplaceAll(out, "{VERSION_COMMA}", version_comma)
ioutil.WriteFile(outfile, []byte(out), 0644)
}

99
cmd/package_macos/main.go Normal file
View File

@@ -0,0 +1,99 @@
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"strconv"
"strings"
)
var plist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>yarr</string>
<key>CFBundleDisplayName</key>
<string>yarr</string>
<key>CFBundleIdentifier</key>
<string>nkanaev.yarr</string>
<key>CFBundleVersion</key>
<string>VERSION</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleExecutable</key>
<string>yarr</string>
<key>CFBundleIconFile</key>
<string>icon</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.news</string>
<key>NSHighResolutionCapable</key>
<string>True</string>
<key>LSMinimumSystemVersion</key>
<string>10.13</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2020 nkanaev. All rights reserved.</string>
</dict>
</plist>
`
func run(cmd ...string) {
fmt.Println(cmd)
err := exec.Command(cmd[0], cmd[1:]...).Run()
if err != nil {
log.Fatal(err)
}
}
func main() {
var version, outdir string
flag.StringVar(&version, "version", "0.0", "")
flag.StringVar(&outdir, "outdir", "", "")
flag.Parse()
outfile := "yarr"
binDir := path.Join(outdir, "yarr.app", "Contents/MacOS")
resDir := path.Join(outdir, "yarr.app", "Contents/Resources")
plistFile := path.Join(outdir, "yarr.app", "Contents/Info.plist")
pkginfoFile := path.Join(outdir, "yarr.app", "Contents/PkgInfo")
os.MkdirAll(binDir, 0700)
os.MkdirAll(resDir, 0700)
f, _ := ioutil.ReadFile(path.Join(outdir, outfile))
ioutil.WriteFile(path.Join(binDir, outfile), f, 0755)
ioutil.WriteFile(plistFile, []byte(strings.Replace(plist, "VERSION", version, 1)), 0644)
ioutil.WriteFile(pkginfoFile, []byte("APPL????"), 0644)
iconFile := path.Join(outdir, "icon.png")
iconsetDir := path.Join(outdir, "icon.iconset")
os.Mkdir(iconsetDir, 0700)
for _, res := range []int{1024, 512, 256, 128, 64, 32, 16} {
outfile := fmt.Sprintf("icon_%dx%d.png", res, res)
if res == 1024 || res == 64 {
outfile = fmt.Sprintf("icon_%dx%d@2x.png", res/2, res/2)
}
cmd := []string{
"sips", "-s", "format", "png", "--resampleWidth", strconv.Itoa(res),
iconFile, "--out", path.Join(iconsetDir, outfile),
}
run(cmd...)
}
icnsFile := path.Join(resDir, "icon.icns")
run("iconutil", "-c", "icns", iconsetDir, "-o", icnsFile)
}

View File

@@ -90,10 +90,6 @@ func main() {
log.SetOutput(os.Stdout) log.SetOutput(os.Stdout)
} }
if open && strings.HasPrefix(addr, "unix:") {
log.Fatal("Cannot open ", addr, " in browser")
}
if db == "" { if db == "" {
configPath, err := os.UserConfigDir() configPath, err := os.UserConfigDir()
if err != nil { if err != nil {

View File

@@ -1,33 +1,21 @@
## Compilation ## Compilation
Prerequisies: Install `Go >= 1.17` and `GCC`. Get the source code:
* Go >= 1.23
* C Compiler (GCC / Clang / ...)
* Zig >= 0.14.0 (optional, for cross-compiling CLI versions)
* binutils (optional, for building Windows GUI version)
Get the source code:
git clone https://github.com/nkanaev/yarr.git git clone https://github.com/nkanaev/yarr.git
Compile: Then run one of the corresponding commands:
# create cli for the host OS/architecture # create an executable for the host os
make host # out/yarr make build_macos # -> _output/macos/yarr.app
make build_linux # -> _output/linux/yarr
make build_windows # -> _output/windows/yarr.exe
# create GUI, works only in the target OS # host-specific cli version (no gui)
make windows_amd64_gui # out/windows_amd64_gui/yarr.exe make build_default # -> _output/yarr
make windows_arm64_gui # out/windows_arm64_gui/yarr.exe
make darwin_arm64_gui # out/darwin_arm64_gui/yarr.app
make darwin_amd64_gui # out/darwin_amd64_gui/yarr.app
# create cli, cross-compiles within any OS/architecture # ... or start a dev server locally
make linux_amd64 make serve # starts a server at http://localhost:7070
make linux_arm64
make linux_armv7
make windows_amd64
make windows_arm64
# ... or build a docker image # ... or build a docker image
docker build -t yarr -f etc/dockerfile . docker build -t yarr -f etc/dockerfile .

View File

@@ -1,15 +1,9 @@
# upcoming # upcoming
- (new) serve on unix socket (thanks to @rvighne)
- (fix) smooth scrolling on iOS (thanks to gatheraled)
# v2.5 (2025-03-26)
- (new) Fever API support (thanks to @icefed) - (new) Fever API support (thanks to @icefed)
- (new) editable feed link (thanks to @adaszko) - (new) editable feed link (thanks to @adaszko)
- (new) switch to feed by clicking the title in the article page (thanks to @tarasglek for suggestion) - (new) switch to feed by clicking the title in the article page (thanks to @tarasglek for suggestion)
- (new) support multiple media links - (new) support multiple media links
- (new) next/prev article navigation buttons (thanks to @tillcash)
- (fix) duplicate articles caused by the same feed addition (thanks to @adaszko) - (fix) duplicate articles caused by the same feed addition (thanks to @adaszko)
- (fix) relative article links (thanks to @adazsko for the report) - (fix) relative article links (thanks to @adazsko for the report)
- (fix) atom article links stored in id element (thanks to @adazsko for the report) - (fix) atom article links stored in id element (thanks to @adazsko for the report)
@@ -23,7 +17,6 @@
- (etc) load external images with no-referrer policy (thanks to @tillcash for the report) - (etc) load external images with no-referrer policy (thanks to @tillcash for the report)
- (etc) open external links with no-referrer policy (thanks to @donovanglover) - (etc) open external links with no-referrer policy (thanks to @donovanglover)
- (etc) show article content in the list if title is missing (thanks to @asimpson for suggestion) - (etc) show article content in the list if title is missing (thanks to @asimpson for suggestion)
- (etc) accessibility improvements (thanks to @tseykovets)
# v2.4 (2023-08-15) # v2.4 (2023-08-15)

View File

@@ -1,14 +1,14 @@
FROM golang:alpine3.21 AS build FROM golang:alpine3.18 AS build
RUN apk add build-base git RUN apk add build-base git
WORKDIR /src WORKDIR /src
COPY . . COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \ RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/root/go/pkg \
--mount=type=cache,target=/root/go/pkg \ make build_linux
make host
FROM alpine:latest FROM alpine:latest
RUN apk add --no-cache ca-certificates && update-ca-certificates RUN apk add --no-cache ca-certificates && \
COPY --from=build /src/out/yarr /usr/local/bin/yarr update-ca-certificates
COPY --from=build /src/_output/linux/yarr /usr/local/bin/yarr
EXPOSE 7070 EXPOSE 7070
ENTRYPOINT ["/usr/local/bin/yarr"] ENTRYPOINT ["/usr/local/bin/yarr"]
CMD ["-addr", "0.0.0.0:7070", "-db", "/data/yarr.db"] CMD ["-addr", "0.0.0.0:7070", "-db", "/data/yarr.db"]

View File

@@ -12,9 +12,9 @@ RUN env DEBIAN_FRONTEND=noninteractive \
apt install -y qemu-user qemu-user-static apt install -y qemu-user qemu-user-static
# Install Golang # Install Golang
RUN wget --quiet https://go.dev/dl/go1.24.1.linux-amd64.tar.gz && \ RUN wget --quiet https://go.dev/dl/go1.18.2.linux-amd64.tar.gz && \
rm -rf /usr/local/go && \ rm -rf /usr/local/go && \
tar -C /usr/local -xzf go1.24.1.linux-amd64.tar.gz tar -C /usr/local -xzf go1.18.2.linux-amd64.tar.gz
ENV PATH=$PATH:/usr/local/go/bin ENV PATH=$PATH:/usr/local/go/bin
# Copy source code # Copy source code
@@ -27,12 +27,18 @@ RUN env \
CC=aarch64-linux-gnu-gcc \ CC=aarch64-linux-gnu-gcc \
CGO_ENABLED=1 \ CGO_ENABLED=1 \
GOOS=linux GOARCH=arm64 \ GOOS=linux GOARCH=arm64 \
make host && mv out/yarr /root/out/yarr.arm64 go build \
-tags "sqlite_foreign_keys linux" \
-ldflags="-s -w" \
-o /root/out/yarr.arm64 ./cmd/yarr
RUN env \ RUN env \
CC=arm-linux-gnueabihf-gcc \ CC=arm-linux-gnueabihf-gcc \
CGO_ENABLED=1 \ CGO_ENABLED=1 \
GOOS=linux GOARCH=arm GOARM=7 \ GOOS=linux GOARCH=arm GOARM=7 \
make host && mv out/yarr /root/out/yarr.armv7 go build \
-tags "sqlite_foreign_keys linux" \
-ldflags="-s -w" \
-o /root/out/yarr.arm7 ./cmd/yarr
CMD ["/bin/bash"] CMD ["/bin/bash"]

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -10,7 +10,7 @@ Name=yarr
Exec=$HOME/.local/bin/yarr -open Exec=$HOME/.local/bin/yarr -open
Icon=yarr Icon=yarr
Type=Application Type=Application
Categories=Internet;Network;News;Feed; Categories=Internet;
END END
if [[ ! -d "$HOME/.local/share/icons" ]]; then if [[ ! -d "$HOME/.local/share/icons" ]]; then

View File

@@ -1,62 +0,0 @@
#/bin/sh
set -e
usage() {
echo "usage: $0 VERSION path/to/icon.icns path/to/binary output/dir"
}
if [ $# -eq 0 ]; then
usage
exit
fi
VERSION=$1
ICNFILE=$2
BINFILE=$3
OUTPATH=$4
mkdir -p $OUTPATH/yarr.app/Contents/MacOS
mkdir -p $OUTPATH/yarr.app/Contents/Resources
mv $BINFILE $OUTPATH/yarr.app/Contents/MacOS/yarr
cp $ICNFILE $OUTPATH/yarr.app/Contents/Resources/icon.icns
chmod u+x $OUTPATH/yarr.app/Contents/MacOS/yarr
echo -n 'APPL????' >$OUTPATH/yarr.app/Contents/PkgInfo
cat <<EOF >$OUTPATH/yarr.app/Contents/Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>yarr</string>
<key>CFBundleDisplayName</key>
<string>yarr</string>
<key>CFBundleIdentifier</key>
<string>nkanaev.yarr</string>
<key>CFBundleVersion</key>
<string>$VERSION</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleExecutable</key>
<string>yarr</string>
<key>CFBundleIconFile</key>
<string>icon</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.news</string>
<key>NSHighResolutionCapable</key>
<string>True</string>
<key>LSMinimumSystemVersion</key>
<string>10.13</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2020 nkanaev. All rights reserved.</string>
</dict>
</plist>
EOF

View File

@@ -1,89 +0,0 @@
#!/bin/bash
set -e
# Function to display usage information
usage() {
echo "Usage: $0 [-version VERSION] [-outfile FILENAME]"
echo " -version VERSION Set the version number (default: 0.0)"
echo " -outfile FILENAME Set the output file name (default: versioninfo.rc)"
echo ""
echo "This script generates a Windows resource file with version information."
exit 1
}
# Default values
version="0.0"
outfile="versioninfo.rc"
# Check if help is requested
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
usage
fi
if [ $# -eq 0 ]; then
usage
fi
# Parse command-line options
while [[ $# -gt 0 ]]; do
case $1 in
-version)
if [[ -z "$2" || "$2" == -* ]]; then
echo "Error: Missing value for -version parameter"
usage
fi
version="$2"
shift 2
;;
-outfile)
if [[ -z "$2" || "$2" == -* ]]; then
echo "Error: Missing value for -outfile parameter"
usage
fi
outfile="$2"
shift 2
;;
*)
echo "Error: Unknown parameter: $1"
usage
;;
esac
done
# Replace dots with commas for version_comma
version_comma="${version//./,}"
# Use a here document for the template with ENDFILE delimiter
cat <<ENDFILE > "$outfile"
1 VERSIONINFO
FILEVERSION $version_comma,0,0
PRODUCTVERSION $version_comma,0,0
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "080904E4"
BEGIN
VALUE "CompanyName", "Old MacDonald's Farm"
VALUE "FileDescription", "Yet another RSS reader"
VALUE "FileVersion", "$version"
VALUE "InternalName", "yarr"
VALUE "LegalCopyright", "nkanaev"
VALUE "OriginalFilename", "yarr.exe"
VALUE "ProductName", "yarr"
VALUE "ProductVersion", "$version"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x809, 1252
END
END
1 ICON "icon.ico"
ENDFILE
# Set the correct permissions
chmod 644 "$outfile"
echo "Generated $outfile with version $version"

12
go.mod
View File

@@ -1,13 +1,11 @@
module github.com/nkanaev/yarr module github.com/nkanaev/yarr
go 1.23.0 go 1.18
toolchain go1.23.5
require ( require (
github.com/mattn/go-sqlite3 v1.14.24 github.com/mattn/go-sqlite3 v1.14.7
golang.org/x/net v0.38.0 golang.org/x/net v0.33.0
golang.org/x/sys v0.31.0 golang.org/x/sys v0.28.0
) )
require golang.org/x/text v0.23.0 // indirect require golang.org/x/text v0.21.0 // indirect

78
go.sum
View File

@@ -1,8 +1,70 @@
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@@ -1,89 +1,34 @@
VERSION=2.5 VERSION=2.4
GITHASH=$(shell git rev-parse --short=8 HEAD) GITHASH=$(shell git rev-parse --short=8 HEAD)
GO_TAGS = sqlite_foreign_keys sqlite_json GO_TAGS = sqlite_foreign_keys sqlite_json
GO_LDFLAGS = -s -w -X 'main.Version=$(VERSION)' -X 'main.GitHash=$(GITHASH)' GO_LDFLAGS = -s -w -X 'main.Version=$(VERSION)' -X 'main.GitHash=$(GITHASH)'
GO_FLAGS = -tags "$(GO_TAGS)" -ldflags="$(GO_LDFLAGS)" export GOARCH ?= amd64
GO_FLAGS_GUI = -tags "$(GO_TAGS) gui" -ldflags="$(GO_LDFLAGS)" export CGO_ENABLED = 1
GO_FLAGS_GUI_WIN = -tags "$(GO_TAGS) gui" -ldflags="$(GO_LDFLAGS) -H windowsgui"
export CGO_ENABLED=1 build_default:
mkdir -p _output
go build -tags "$(GO_TAGS)" -ldflags="$(GO_LDFLAGS)" -o _output/yarr ./cmd/yarr
default: test host build_macos:
mkdir -p _output/macos
GOOS=darwin go build -tags "$(GO_TAGS) macos" -ldflags="$(GO_LDFLAGS)" -o _output/macos/yarr ./cmd/yarr
cp src/platform/icon.png _output/macos/icon.png
go run ./cmd/package_macos -outdir _output/macos -version "$(VERSION)"
# platform-specific files build_linux:
mkdir -p _output/linux
GOOS=linux go build -tags "$(GO_TAGS) linux" -ldflags="$(GO_LDFLAGS)" -o _output/linux/yarr ./cmd/yarr
etc/icon.icns: etc/icon_macos.png build_windows:
mkdir -p etc/icon.iconset mkdir -p _output/windows
sips -s format png --resampleWidth 1024 etc/icon_macos.png --out etc/icon.iconset/icon_512x512@2x.png go run ./cmd/generate_versioninfo -version "$(VERSION)" -outfile src/platform/versioninfo.rc
sips -s format png --resampleWidth 512 etc/icon_macos.png --out etc/icon.iconset/icon_512x512.png
sips -s format png --resampleWidth 256 etc/icon_macos.png --out etc/icon.iconset/icon_256x256.png
sips -s format png --resampleWidth 128 etc/icon_macos.png --out etc/icon.iconset/icon_128x128.png
sips -s format png --resampleWidth 64 etc/icon_macos.png --out etc/icon.iconset/icon_32x32@2x.png
sips -s format png --resampleWidth 32 etc/icon_macos.png --out etc/icon.iconset/icon_32x32.png
sips -s format png --resampleWidth 16 etc/icon_macos.png --out etc/icon.iconset/icon_16x16.png
iconutil -c icns etc/icon.iconset -o etc/icon.icns
src/platform/versioninfo.rc:
./etc/windows_versioninfo.sh -version "$(VERSION)" -outfile src/platform/versioninfo.rc
windres -i src/platform/versioninfo.rc -O coff -o src/platform/versioninfo.syso windres -i src/platform/versioninfo.rc -O coff -o src/platform/versioninfo.syso
GOOS=windows go build -tags "$(GO_TAGS) windows" -ldflags="$(GO_LDFLAGS) -H windowsgui" -o _output/windows/yarr.exe ./cmd/yarr
# build targets
host:
go build $(GO_FLAGS) -o out/yarr ./cmd/yarr
darwin_amd64:
# cross-compilation not supported: CC="zig cc -target x86_64-macos-none"
GOOS=darwin GOARCH=arm64 go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
darwin_arm64:
# cross-compilation not supported: CC="zig cc -target aarch64-macos-none"
GOOS=darwin GOARCH=arm64 go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
linux_amd64:
CC="zig cc -target x86_64-linux-musl -O2 -g0" CGO_CFLAGS="-D_LARGEFILE64_SOURCE" GOOS=linux GOARCH=amd64 \
go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
linux_arm64:
CC="zig cc -target aarch64-linux-musl -O2 -g0" CGO_CFLAGS="-D_LARGEFILE64_SOURCE" GOOS=linux GOARCH=arm64 \
go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
linux_armv7:
CC="zig cc -target arm-linux-musleabihf -O2 -g0" CGO_CFLAGS="-D_LARGEFILE64_SOURCE" GOOS=linux GOARCH=arm GOARM=7 \
go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
windows_amd64:
CC="zig cc -target x86_64-windows-gnu" GOOS=windows GOARCH=amd64 go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
windows_arm64:
CC="zig cc -target aarch64-windows-gnu" GOOS=windows GOARCH=arm64 go build $(GO_FLAGS) -o out/$@/yarr ./cmd/yarr
darwin_arm64_gui: etc/icon.icns
GOOS=darwin GOARCH=arm64 go build $(GO_FLAGS_GUI) -o out/$@/yarr ./cmd/yarr
./etc/macos_package.sh $(VERSION) etc/icon.icns out/$@/yarr out/$@
darwin_amd64_gui: etc/icon.icns
GOOS=darwin GOARCH=amd64 go build $(GO_FLAGS_GUI) -o out/$@/yarr ./cmd/yarr
./etc/macos_package.sh $(VERSION) etc/icon.icns out/$@/yarr out/$@
windows_amd64_gui: src/platform/versioninfo.rc
GOOS=windows GOARCH=amd64 go build $(GO_FLAGS_GUI_WIN) -o out/$@/yarr.exe ./cmd/yarr
windows_arm64_gui: src/platform/versioninfo.rc
GOOS=windows GOARCH=arm64 go build $(GO_FLAGS_GUI_WIN) -o out/$@/yarr.exe ./cmd/yarr
serve: serve:
go run $(GO_FLAGS) ./cmd/yarr -db local.db go run -tags "$(GO_TAGS)" ./cmd/yarr -db local.db
test: test:
go test $(GO_FLAGS) ./... go test -tags "$(GO_TAGS)" ./...
.PHONY: \
host \
darwin_amd64 darwin_amd64_gui \
darwin_arm64 darwin_arm64_gui \
windows_amd64 windows_amd64_gui \
windows_arm64 windows_arm64_gui \
serve test

View File

@@ -9,21 +9,21 @@ The app is a single binary with an embedded database (SQLite).
## usage ## usage
The latest prebuilt binaries for Linux/MacOS/Windows are available The latest prebuilt binaries for Linux/MacOS/Windows AMD64 are available
[here](https://github.com/nkanaev/yarr/releases/latest). [here](https://github.com/nkanaev/yarr/releases/latest). Installation instructions:
The archives follow the naming convention `yarr_{OS}_{ARCH}[_gui].zip`, where:
* `OS` is the target operating system * MacOS
* `ARCH` is the CPU architecture (`arm64` for AArch64, `amd64` for X86-64)
* `-gui` indicates that the binary ships with the GUI (tray icon), and is a command line application if omitted
Usage instructions: Download `yarr-*-macos64.zip`, unzip it, place `yarr.app` in `/Applications` folder, [open the app][macos-open], click the anchor menu bar icon, select "Open".
* MacOS: place `yarr.app` in `/Applications` folder, [open the app][macos-open], click the anchor menu bar icon, select "Open". * Windows
* Windows: open `yarr.exe`, click the anchor system tray icon, select "Open". Download `yarr-*-windows64.zip`, unzip it, open `yarr.exe`, click the anchor system tray icon, select "Open".
* Linux: place `yarr` in `$HOME/.local/bin` and run [the script](etc/install-linux.sh). * Linux
Download `yarr-*-linux64.zip`, unzip it, place `yarr` in `$HOME/.local/bin`
and run [the script](etc/install-linux.sh).
[macos-open]: https://support.apple.com/en-gb/guide/mac-help/mh40616/mac [macos-open]: https://support.apple.com/en-gb/guide/mac-help/mh40616/mac

View File

@@ -122,7 +122,7 @@
</button> </button>
</dropdown> </dropdown>
</div> </div>
<div id="feed-list-scroll" class="p-2 overflow-auto scroll-touch border-top flex-grow-1"> <div id="feed-list-scroll" class="p-2 overflow-auto border-top flex-grow-1">
<label class="selectgroup"> <label class="selectgroup">
<input type="radio" name="feed" value="" v-model="feedSelected"> <input type="radio" name="feed" value="" v-model="feedSelected">
<div class="selectgroup-label d-flex align-items-center w-100"> <div class="selectgroup-label d-flex align-items-center w-100">
@@ -272,7 +272,7 @@
</button> </button>
</dropdown> </dropdown>
</div> </div>
<div id="item-list-scroll" class="p-2 overflow-auto scroll-touch border-top flex-grow-1" v-scroll="loadMoreItems" ref="itemlist"> <div id="item-list-scroll" class="p-2 overflow-auto border-top flex-grow-1" v-scroll="loadMoreItems" ref="itemlist">
<label v-for="item in items" :key="item.id" <label v-for="item in items" :key="item.id"
class="selectgroup"> class="selectgroup">
<input type="radio" name="item" :value="item.id" v-model="itemSelected"> <input type="radio" name="item" :value="item.id" v-model="itemSelected">
@@ -347,7 +347,7 @@
</div> </div>
<div v-if="itemSelectedDetails" <div v-if="itemSelectedDetails"
ref="content" ref="content"
class="content px-4 pt-3 pb-5 border-top overflow-auto scroll-touch" class="content px-4 pt-3 pb-5 border-top overflow-auto"
:class="{'font-serif': theme.font == 'serif', 'font-monospace': theme.font == 'monospace'}" :class="{'font-serif': theme.font == 'serif', 'font-monospace': theme.font == 'monospace'}"
:style="{'font-size': theme.size + 'rem'}"> :style="{'font-size': theme.size + 'rem'}">
<div class="content-wrapper"> <div class="content-wrapper">
@@ -365,7 +365,7 @@
<div v-if="contentImages.length"> <div v-if="contentImages.length">
<figure v-for="media in contentImages"> <figure v-for="media in contentImages">
<img :src="media.url" loading="lazy"> <img :src="media.url" loading="lazy">
<figcaption v-if="media.description">{{ media.description }}</figcaption> <figcaption v-if="media.description" v-html="media.description"></figcaption>
</figure> </figure>
</div> </div>
<audio class="w-100" controls v-for="media in contentAudios" :src="media.url"></audio> <audio class="w-100" controls v-for="media in contentAudios" :src="media.url"></audio>

View File

@@ -100,10 +100,6 @@ select.form-control:not([multiple]):not([size]) {
padding-right: 0; padding-right: 0;
} }
.scroll-touch {
-webkit-overflow-scrolling: touch;
}
/* custom elements */ /* custom elements */
.font-serif { .font-serif {

View File

@@ -274,9 +274,9 @@ func TestRSSMultipleMedia(t *testing.T) {
GUID: "http://example.com/posts/1", GUID: "http://example.com/posts/1",
URL: "http://example.com/posts/1", URL: "http://example.com/posts/1",
MediaLinks: []MediaLink{ MediaLinks: []MediaLink{
{URL: "https://example.com/path/to/image1.png", Type: "image", Description: "description 1"}, {URL:"https://example.com/path/to/image1.png", Type:"image", Description:"description 1"},
{URL: "https://example.com/path/to/image2.png", Type: "image", Description: "description 2"}, {URL:"https://example.com/path/to/image2.png", Type:"image", Description:"description 2"},
{URL: "https://example.com/path/to/video1.mp4", Type: "video", Description: "video description"}, {URL:"https://example.com/path/to/video1.mp4", Type:"video", Description:"video description"},
}, },
}, },
} }

View File

@@ -1,4 +1,5 @@
//go:build !windows //go:build !windows
// +build !windows
package platform package platform

View File

@@ -1,5 +1,3 @@
//go:build windows
package platform package platform
import ( import (

View File

@@ -1,4 +1,5 @@
//go:build (darwin || windows) && gui //go:build macos || windows
// +build macos windows
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build !gui //go:build !windows && !macos
// +build !windows,!macos
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build darwin && gui //go:build macos
// +build macos
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build windows && gui //go:build windows
// +build windows
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build linux || freebsd //go:build !windows && !darwin
// +build !windows,!darwin
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build darwin //go:build darwin
// +build darwin
package platform package platform

View File

@@ -1,4 +1,5 @@
//go:build windows //go:build windows
// +build windows
package platform package platform

View File

@@ -2,10 +2,7 @@ package server
import ( import (
"log" "log"
"net"
"net/http" "net/http"
"os"
"strings"
"sync" "sync"
"github.com/nkanaev/yarr/src/storage" "github.com/nkanaev/yarr/src/storage"
@@ -56,31 +53,14 @@ func (s *Server) Start() {
s.worker.RefreshFeeds() s.worker.RefreshFeeds()
} }
var ln net.Listener httpserver := &http.Server{Addr: s.Addr, Handler: s.handler()}
var err error var err error
if path, isUnix := strings.CutPrefix(s.Addr, "unix:"); isUnix {
err = os.Remove(path)
if err != nil {
log.Print(err)
}
ln, err = net.Listen("unix", path)
} else {
ln, err = net.Listen("tcp", s.Addr)
}
if err != nil {
log.Fatal(err)
}
httpserver := &http.Server{Handler: s.handler()}
if s.CertFile != "" && s.KeyFile != "" { if s.CertFile != "" && s.KeyFile != "" {
err = httpserver.ServeTLS(ln, s.CertFile, s.KeyFile) err = httpserver.ListenAndServeTLS(s.CertFile, s.KeyFile)
ln.Close()
} else { } else {
err = httpserver.Serve(ln) err = httpserver.ListenAndServe()
} }
if err != http.ErrServerClosed { if err != http.ErrServerClosed {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -310,19 +310,22 @@ func m09_change_item_index(tx *sql.Tx) error {
func m10_add_item_medialinks(tx *sql.Tx) error { func m10_add_item_medialinks(tx *sql.Tx) error {
sql := ` sql := `
alter table items add column media_links json; alter table items add column media_links blob;
update items set media_links = case update items set media_links =
when coalesce(image, '') != '' and coalesce(podcast_url, '') != '' iif(
then json_array(json_object('type', 'image', 'url', image), json_object('type', 'audio', 'url', podcast_url)) coalesce(image, '') != '' and coalesce(podcast_url, '') != '',
json_array(json_object('type', 'image', 'url', image), json_object('type', 'audio', 'url', podcast_url)),
iif(
coalesce(image, '') != '',
json_array(json_object('type', 'image', 'url', image)),
iif(
coalesce(podcast_url, '') != '',
json_array(json_object('type', 'audio', 'url', podcast_url)),
null
)
)
);
when coalesce(image, '') != ''
then json_array(json_object('type', 'image', 'url', image))
when coalesce(podcast_url, '') != ''
then json_array(json_object('type', 'audio', 'url', podcast_url))
else null
end;
alter table items drop column image; alter table items drop column image;
alter table items drop column podcast_url; alter table items drop column podcast_url;
` `

View File

@@ -1,23 +1,23 @@
go-sqlite3 go-sqlite3
========== ==========
[![Go Reference](https://pkg.go.dev/badge/github.com/mattn/go-sqlite3.svg)](https://pkg.go.dev/github.com/mattn/go-sqlite3) [![GoDoc Reference](https://godoc.org/github.com/mattn/go-sqlite3?status.svg)](http://godoc.org/github.com/mattn/go-sqlite3)
[![GitHub Actions](https://github.com/mattn/go-sqlite3/workflows/Go/badge.svg)](https://github.com/mattn/go-sqlite3/actions?query=workflow%3AGo) [![GitHub Actions](https://github.com/mattn/go-sqlite3/workflows/Go/badge.svg)](https://github.com/mattn/go-sqlite3/actions?query=workflow%3AGo)
[![Financial Contributors on Open Collective](https://opencollective.com/mattn-go-sqlite3/all/badge.svg?label=financial+contributors)](https://opencollective.com/mattn-go-sqlite3) [![Financial Contributors on Open Collective](https://opencollective.com/mattn-go-sqlite3/all/badge.svg?label=financial+contributors)](https://opencollective.com/mattn-go-sqlite3)
[![codecov](https://codecov.io/gh/mattn/go-sqlite3/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-sqlite3) [![codecov](https://codecov.io/gh/mattn/go-sqlite3/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-sqlite3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3) [![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3)
Latest stable version is v1.14 or later, not v2. Latest stable version is v1.14 or later not v2.
~~**NOTE:** The increase to v2 was an accident. There were no major changes or features.~~ ~~**NOTE:** The increase to v2 was an accident. There were no major changes or features.~~
# Description # Description
A sqlite3 driver that conforms to the built-in database/sql interface. sqlite3 driver conforming to the built-in database/sql interface
Supported Golang version: See [.github/workflows/go.yaml](./.github/workflows/go.yaml). Supported Golang version: See [.github/workflows/go.yaml](./.github/workflows/go.yaml)
This package follows the official [Golang Release Policy](https://golang.org/doc/devel/release.html#policy). [This package follows the official Golang Release Policy.](https://golang.org/doc/devel/release.html#policy)
### Overview ### Overview
@@ -40,7 +40,7 @@ This package follows the official [Golang Release Policy](https://golang.org/doc
- [Alpine](#alpine) - [Alpine](#alpine)
- [Fedora](#fedora) - [Fedora](#fedora)
- [Ubuntu](#ubuntu) - [Ubuntu](#ubuntu)
- [macOS](#mac-osx) - [Mac OSX](#mac-osx)
- [Windows](#windows) - [Windows](#windows)
- [Errors](#errors) - [Errors](#errors)
- [User Authentication](#user-authentication) - [User Authentication](#user-authentication)
@@ -64,7 +64,7 @@ This package follows the official [Golang Release Policy](https://golang.org/doc
# Installation # Installation
This package can be installed with the `go get` command: This package can be installed with the go get command:
go get github.com/mattn/go-sqlite3 go get github.com/mattn/go-sqlite3
@@ -72,28 +72,28 @@ _go-sqlite3_ is *cgo* package.
If you want to build your app using go-sqlite3, you need gcc. If you want to build your app using go-sqlite3, you need gcc.
However, after you have built and installed _go-sqlite3_ with `go install github.com/mattn/go-sqlite3` (which requires gcc), you can build your app without relying on gcc in future. However, after you have built and installed _go-sqlite3_ with `go install github.com/mattn/go-sqlite3` (which requires gcc), you can build your app without relying on gcc in future.
***Important: because this is a `CGO` enabled package, you are required to set the environment variable `CGO_ENABLED=1` and have a `gcc` compiler present within your path.*** ***Important: because this is a `CGO` enabled package you are required to set the environment variable `CGO_ENABLED=1` and have a `gcc` compile present within your path.***
# API Reference # API Reference
API documentation can be found [here](http://godoc.org/github.com/mattn/go-sqlite3). API documentation can be found here: http://godoc.org/github.com/mattn/go-sqlite3
Examples can be found under the [examples](./_example) directory. Examples can be found under the [examples](./_example) directory
# Connection String # Connection String
When creating a new SQLite database or connection to an existing one, with the file name additional options can be given. When creating a new SQLite database or connection to an existing one, with the file name additional options can be given.
This is also known as a DSN (Data Source Name) string. This is also known as a DSN string. (Data Source Name).
Options are append after the filename of the SQLite database. Options are append after the filename of the SQLite database.
The database filename and options are separated by an `?` (Question Mark). The database filename and options are seperated by an `?` (Question Mark).
Options should be URL-encoded (see [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)). Options should be URL-encoded (see [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)).
This also applies when using an in-memory database instead of a file. This also applies when using an in-memory database instead of a file.
Options can be given using the following format: `KEYWORD=VALUE` and multiple options can be combined with the `&` ampersand. Options can be given using the following format: `KEYWORD=VALUE` and multiple options can be combined with the `&` ampersand.
This library supports DSN options of SQLite itself and provides additional options. This library supports dsn options of SQLite itself and provides additional options.
Boolean values can be one of: Boolean values can be one of:
* `0` `no` `false` `off` * `0` `no` `false` `off`
@@ -138,23 +138,24 @@ file:test.db?cache=shared&mode=memory
This package allows additional configuration of features available within SQLite3 to be enabled or disabled by golang build constraints also known as build `tags`. This package allows additional configuration of features available within SQLite3 to be enabled or disabled by golang build constraints also known as build `tags`.
Click [here](https://golang.org/pkg/go/build/#hdr-Build_Constraints) for more information about build tags / constraints. [Click here for more information about build tags / constraints.](https://golang.org/pkg/go/build/#hdr-Build_Constraints)
### Usage ### Usage
If you wish to build this library with additional extensions / features, use the following command: If you wish to build this library with additional extensions / features.
Use the following command.
```bash ```bash
go build -tags "<FEATURE>" go build --tags "<FEATURE>"
``` ```
For available features, see the extension list. For available features see the extension list.
When using multiple build tags, all the different tags should be space delimited. When using multiple build tags, all the different tags should be space delimted.
Example: Example:
```bash ```bash
go build -tags "icu json1 fts5 secure_delete" go build --tags "icu json1 fts5 secure_delete"
``` ```
### Feature / Extension List ### Feature / Extension List
@@ -165,7 +166,6 @@ go build -tags "icu json1 fts5 secure_delete"
| Allow URI Authority | sqlite_allow_uri_authority | URI filenames normally throws an error if the authority section is not either empty or "localhost".<br><br>However, if SQLite is compiled with the SQLITE_ALLOW_URI_AUTHORITY compile-time option, then the URI is converted into a Uniform Naming Convention (UNC) filename and passed down to the underlying operating system that way | | Allow URI Authority | sqlite_allow_uri_authority | URI filenames normally throws an error if the authority section is not either empty or "localhost".<br><br>However, if SQLite is compiled with the SQLITE_ALLOW_URI_AUTHORITY compile-time option, then the URI is converted into a Uniform Naming Convention (UNC) filename and passed down to the underlying operating system that way |
| App Armor | sqlite_app_armor | When defined, this C-preprocessor macro activates extra code that attempts to detect misuse of the SQLite API, such as passing in NULL pointers to required parameters or using objects after they have been destroyed. <br><br>App Armor is not available under `Windows`. | | App Armor | sqlite_app_armor | When defined, this C-preprocessor macro activates extra code that attempts to detect misuse of the SQLite API, such as passing in NULL pointers to required parameters or using objects after they have been destroyed. <br><br>App Armor is not available under `Windows`. |
| Disable Load Extensions | sqlite_omit_load_extension | Loading of external extensions is enabled by default.<br><br>To disable extension loading add the build tag `sqlite_omit_load_extension`. | | Disable Load Extensions | sqlite_omit_load_extension | Loading of external extensions is enabled by default.<br><br>To disable extension loading add the build tag `sqlite_omit_load_extension`. |
| Enable Serialization with `libsqlite3` | sqlite_serialize | Serialization and deserialization of a SQLite database is available by default, unless the build tag `libsqlite3` is set.<br><br>To enable this functionality even if `libsqlite3` is set, add the build tag `sqlite_serialize`. |
| Foreign Keys | sqlite_foreign_keys | This macro determines whether enforcement of foreign key constraints is enabled or disabled by default for new database connections.<br><br>Each database connection can always turn enforcement of foreign key constraints on and off and run-time using the foreign_keys pragma.<br><br>Enforcement of foreign key constraints is normally off by default, but if this compile-time parameter is set to 1, enforcement of foreign key constraints will be on by default | | Foreign Keys | sqlite_foreign_keys | This macro determines whether enforcement of foreign key constraints is enabled or disabled by default for new database connections.<br><br>Each database connection can always turn enforcement of foreign key constraints on and off and run-time using the foreign_keys pragma.<br><br>Enforcement of foreign key constraints is normally off by default, but if this compile-time parameter is set to 1, enforcement of foreign key constraints will be on by default |
| Full Auto Vacuum | sqlite_vacuum_full | Set the default auto vacuum to full | | Full Auto Vacuum | sqlite_vacuum_full | Set the default auto vacuum to full |
| Incremental Auto Vacuum | sqlite_vacuum_incr | Set the default auto vacuum to incremental | | Incremental Auto Vacuum | sqlite_vacuum_incr | Set the default auto vacuum to incremental |
@@ -173,20 +173,17 @@ go build -tags "icu json1 fts5 secure_delete"
| International Components for Unicode | sqlite_icu | This option causes the International Components for Unicode or "ICU" extension to SQLite to be added to the build | | International Components for Unicode | sqlite_icu | This option causes the International Components for Unicode or "ICU" extension to SQLite to be added to the build |
| Introspect PRAGMAS | sqlite_introspect | This option adds some extra PRAGMA statements. <ul><li>PRAGMA function_list</li><li>PRAGMA module_list</li><li>PRAGMA pragma_list</li></ul> | | Introspect PRAGMAS | sqlite_introspect | This option adds some extra PRAGMA statements. <ul><li>PRAGMA function_list</li><li>PRAGMA module_list</li><li>PRAGMA pragma_list</li></ul> |
| JSON SQL Functions | sqlite_json | When this option is defined in the amalgamation, the JSON SQL functions are added to the build automatically | | JSON SQL Functions | sqlite_json | When this option is defined in the amalgamation, the JSON SQL functions are added to the build automatically |
| Math Functions | sqlite_math_functions | This compile-time option enables built-in scalar math functions. For more information see [Built-In Mathematical SQL Functions](https://www.sqlite.org/lang_mathfunc.html) |
| OS Trace | sqlite_os_trace | This option enables OSTRACE() debug logging. This can be verbose and should not be used in production. |
| Pre Update Hook | sqlite_preupdate_hook | Registers a callback function that is invoked prior to each INSERT, UPDATE, and DELETE operation on a database table. | | Pre Update Hook | sqlite_preupdate_hook | Registers a callback function that is invoked prior to each INSERT, UPDATE, and DELETE operation on a database table. |
| Secure Delete | sqlite_secure_delete | This compile-time option changes the default setting of the secure_delete pragma.<br><br>When this option is not used, secure_delete defaults to off. When this option is present, secure_delete defaults to on.<br><br>The secure_delete setting causes deleted content to be overwritten with zeros. There is a small performance penalty since additional I/O must occur.<br><br>On the other hand, secure_delete can prevent fragments of sensitive information from lingering in unused parts of the database file after it has been deleted. See the documentation on the secure_delete pragma for additional information | | Secure Delete | sqlite_secure_delete | This compile-time option changes the default setting of the secure_delete pragma.<br><br>When this option is not used, secure_delete defaults to off. When this option is present, secure_delete defaults to on.<br><br>The secure_delete setting causes deleted content to be overwritten with zeros. There is a small performance penalty since additional I/O must occur.<br><br>On the other hand, secure_delete can prevent fragments of sensitive information from lingering in unused parts of the database file after it has been deleted. See the documentation on the secure_delete pragma for additional information |
| Secure Delete (FAST) | sqlite_secure_delete_fast | For more information see [PRAGMA secure_delete](https://www.sqlite.org/pragma.html#pragma_secure_delete) | | Secure Delete (FAST) | sqlite_secure_delete_fast | For more information see [PRAGMA secure_delete](https://www.sqlite.org/pragma.html#pragma_secure_delete) |
| Tracing / Debug | sqlite_trace | Activate trace functions | | Tracing / Debug | sqlite_trace | Activate trace functions |
| User Authentication | sqlite_userauth | SQLite User Authentication see [User Authentication](#user-authentication) for more information. | | User Authentication | sqlite_userauth | SQLite User Authentication see [User Authentication](#user-authentication) for more information. |
| Virtual Tables | sqlite_vtable | SQLite Virtual Tables see [SQLite Official VTABLE Documentation](https://www.sqlite.org/vtab.html) for more information, and a [full example here](https://github.com/mattn/go-sqlite3/tree/master/_example/vtable) |
# Compilation # Compilation
This package requires the `CGO_ENABLED=1` environment variable if not set by default, and the presence of the `gcc` compiler. This package requires `CGO_ENABLED=1` ennvironment variable if not set by default, and the presence of the `gcc` compiler.
If you need to add additional CFLAGS or LDFLAGS to the build command, and do not want to modify this package, then this can be achieved by using the `CGO_CFLAGS` and `CGO_LDFLAGS` environment variables. If you need to add additional CFLAGS or LDFLAGS to the build command, and do not want to modify this package. Then this can be achieved by using the `CGO_CFLAGS` and `CGO_LDFLAGS` environment variables.
## Android ## Android
@@ -194,14 +191,14 @@ This package can be compiled for android.
Compile with: Compile with:
```bash ```bash
go build -tags "android" go build --tags "android"
``` ```
For more information see [#201](https://github.com/mattn/go-sqlite3/issues/201) For more information see [#201](https://github.com/mattn/go-sqlite3/issues/201)
# ARM # ARM
To compile for `ARM` use the following environment: To compile for `ARM` use the following environment.
```bash ```bash
env CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \ env CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \
@@ -219,14 +216,15 @@ This library can be cross-compiled.
In some cases you are required to the `CC` environment variable with the cross compiler. In some cases you are required to the `CC` environment variable with the cross compiler.
## Cross Compiling from macOS ## Cross Compiling from MAC OSX
The simplest way to cross compile from macOS is to use [xgo](https://github.com/karalabe/xgo). The simplest way to cross compile from OSX is to use [xgo](https://github.com/karalabe/xgo).
Steps: Steps:
- Install [musl-cross](https://github.com/FiloSottile/homebrew-musl-cross) (`brew install FiloSottile/musl-cross/musl-cross`). - Install [xgo](https://github.com/karalabe/xgo) (`go get github.com/karalabe/xgo`).
- Run `CC=x86_64-linux-musl-gcc CXX=x86_64-linux-musl-g++ GOARCH=amd64 GOOS=linux CGO_ENABLED=1 go build -ldflags "-linkmode external -extldflags -static"`. - Ensure that your project is within your `GOPATH`.
- Run `xgo local/path/to/project`.
Please refer to the project's [README](https://github.com/FiloSottile/homebrew-musl-cross#readme) for further information. Please refer to the project's [README](https://github.com/karalabe/xgo/blob/master/README.md) for further information.
# Google Cloud Platform # Google Cloud Platform
@@ -236,23 +234,23 @@ Please work only with compiled final binaries.
## Linux ## Linux
To compile this package on Linux, you must install the development tools for your linux distribution. To compile this package on Linux you must install the development tools for your linux distribution.
To compile under linux use the build tag `linux`. To compile under linux use the build tag `linux`.
```bash ```bash
go build -tags "linux" go build --tags "linux"
``` ```
If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag. If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag.
``` ```
go build -tags "libsqlite3 linux" go build --tags "libsqlite3 linux"
``` ```
### Alpine ### Alpine
When building in an `alpine` container run the following command before building: When building in an `alpine` container run the following command before building.
``` ```
apk add --update gcc musl-dev apk add --update gcc musl-dev
@@ -270,43 +268,34 @@ sudo yum groupinstall "Development Tools" "Development Libraries"
sudo apt-get install build-essential sudo apt-get install build-essential
``` ```
## macOS ## Mac OSX
macOS should have all the tools present to compile this package. If not, install XCode to add all the developers tools. OSX should have all the tools present to compile this package, if not install XCode this will add all the developers tools.
Required dependency: Required dependency
```bash ```bash
brew install sqlite3 brew install sqlite3
``` ```
For macOS, there is an additional package to install which is required if you wish to build the `icu` extension. For OSX there is an additional package install which is required if you wish to build the `icu` extension.
This additional package can be installed with `homebrew`: This additional package can be installed with `homebrew`.
```bash ```bash
brew upgrade icu4c brew upgrade icu4c
``` ```
To compile for macOS on x86: To compile for Mac OSX.
```bash ```bash
go build -tags "darwin amd64" go build --tags "darwin"
``` ```
To compile for macOS on ARM chips: If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag.
```bash
go build -tags "darwin arm64"
```
If you wish to link directly to libsqlite3, use the `libsqlite3` build tag:
``` ```
# x86 go build --tags "libsqlite3 darwin"
go build -tags "libsqlite3 darwin amd64"
# ARM
go build -tags "libsqlite3 darwin arm64"
``` ```
Additional information: Additional information:
@@ -315,14 +304,14 @@ Additional information:
## Windows ## Windows
To compile this package on Windows, you must have the `gcc` compiler installed. To compile this package on Windows OS you must have the `gcc` compiler installed.
1) Install a Windows `gcc` toolchain. 1) Install a Windows `gcc` toolchain.
2) Add the `bin` folder to the Windows path, if the installer did not do this by default. 2) Add the `bin` folders to the Windows path if the installer did not do this by default.
3) Open a terminal for the TDM-GCC toolchain, which can be found in the Windows Start menu. 3) Open a terminal for the TDM-GCC toolchain, can be found in the Windows Start menu.
4) Navigate to your project folder and run the `go build ...` command for this package. 4) Navigate to your project folder and run the `go build ...` command for this package.
For example the TDM-GCC Toolchain can be found [here](https://jmeubank.github.io/tdm-gcc/). For example the TDM-GCC Toolchain can be found [here](https://sourceforge.net/projects/tdm-gcc/).
## Errors ## Errors
@@ -360,28 +349,28 @@ This package supports the SQLite User Authentication module.
## Compile ## Compile
To use the User authentication module, the package has to be compiled with the tag `sqlite_userauth`. See [Features](#features). To use the User authentication module the package has to be compiled with the tag `sqlite_userauth`. See [Features](#features).
## Usage ## Usage
### Create protected database ### Create protected database
To create a database protected by user authentication, provide the following argument to the connection string `_auth`. To create a database protected by user authentication provide the following argument to the connection string `_auth`.
This will enable user authentication within the database. This option however requires two additional arguments: This will enable user authentication within the database. This option however requires two additional arguments:
- `_auth_user` - `_auth_user`
- `_auth_pass` - `_auth_pass`
When `_auth` is present in the connection string user authentication will be enabled and the provided user will be created When `_auth` is present on the connection string user authentication will be enabled and the provided user will be created
as an `admin` user. After initial creation, the parameter `_auth` has no effect anymore and can be omitted from the connection string. as an `admin` user. After initial creation, the parameter `_auth` has no effect anymore and can be omitted from the connection string.
Example connection strings: Example connection string:
Create an user authentication database with user `admin` and password `admin`: Create an user authentication database with user `admin` and password `admin`.
`file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin` `file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin`
Create an user authentication database with user `admin` and password `admin` and use `SHA1` for the password encoding: Create an user authentication database with user `admin` and password `admin` and use `SHA1` for the password encoding.
`file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin&_auth_crypt=sha1` `file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin&_auth_crypt=sha1`
@@ -407,11 +396,11 @@ salt this can be configured with `_auth_salt`.
### Restrictions ### Restrictions
Operations on the database regarding user management can only be preformed by an administrator user. Operations on the database regarding to user management can only be preformed by an administrator user.
### Support ### Support
The user authentication supports two kinds of users: The user authentication supports two kinds of users
- administrators - administrators
- regular users - regular users
@@ -422,7 +411,7 @@ User management can be done by directly using the `*SQLiteConn` or by SQL.
#### SQL #### SQL
The following sql functions are available for user management: The following sql functions are available for user management.
| Function | Arguments | Description | | Function | Arguments | Description |
|----------|-----------|-------------| |----------|-----------|-------------|
@@ -431,7 +420,7 @@ The following sql functions are available for user management:
| `auth_user_change` | username `string`, password `string`, admin `int` | Function to modify an user. Users can change their own password, but only an administrator can change the administrator flag. | | `auth_user_change` | username `string`, password `string`, admin `int` | Function to modify an user. Users can change their own password, but only an administrator can change the administrator flag. |
| `authUserDelete` | username `string` | Delete an user from the database. Can only be used by an administrator. The current logged in administrator cannot be deleted. This is to make sure their is always an administrator remaining. | | `authUserDelete` | username `string` | Delete an user from the database. Can only be used by an administrator. The current logged in administrator cannot be deleted. This is to make sure their is always an administrator remaining. |
These functions will return an integer: These functions will return an integer.
- 0 (SQLITE_OK) - 0 (SQLITE_OK)
- 23 (SQLITE_AUTH) Failed to perform due to authentication or insufficient privileges - 23 (SQLITE_AUTH) Failed to perform due to authentication or insufficient privileges
@@ -452,7 +441,7 @@ SELECT user_delete('user');
#### *SQLiteConn #### *SQLiteConn
The following functions are available for User authentication from the `*SQLiteConn`: The following functions are available for User authentication from the `*SQLiteConn`.
| Function | Description | | Function | Description |
|----------|-------------| |----------|-------------|
@@ -463,16 +452,16 @@ The following functions are available for User authentication from the `*SQLiteC
### Attached database ### Attached database
When using attached databases, SQLite will use the authentication from the `main` database for the attached database(s). When using attached databases. SQLite will use the authentication from the `main` database for the attached database(s).
# Extensions # Extensions
If you want your own extension to be listed here, or you want to add a reference to an extension; please submit an Issue for this. If you want your own extension to be listed here or you want to add a reference to an extension; please submit an Issue for this.
## Spatialite ## Spatialite
Spatialite is available as an extension to SQLite, and can be used in combination with this repository. Spatialite is available as an extension to SQLite, and can be used in combination with this repository.
For an example, see [shaxbee/go-spatialite](https://github.com/shaxbee/go-spatialite). For an example see [shaxbee/go-spatialite](https://github.com/shaxbee/go-spatialite).
## extension-functions.c from SQLite3 Contrib ## extension-functions.c from SQLite3 Contrib
@@ -482,7 +471,7 @@ extension-functions.c is available as an extension to SQLite, and provides the f
- String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, replace, reverse, proper, padl, padr, padc, strfilter. - String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, replace, reverse, proper, padl, padr, padc, strfilter.
- Aggregate: stdev, variance, mode, median, lower_quartile, upper_quartile - Aggregate: stdev, variance, mode, median, lower_quartile, upper_quartile
For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/dinedal/go-sqlite3-extension-functions). For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/dinedal/go-sqlite3-extension-functions).
# FAQ # FAQ
@@ -502,7 +491,7 @@ For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/
- Can I use this in multiple routines concurrently? - Can I use this in multiple routines concurrently?
Yes for readonly. But not for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209), [#274](https://github.com/mattn/go-sqlite3/issues/274). Yes for readonly. But, No for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209), [#274](https://github.com/mattn/go-sqlite3/issues/274).
- Why I'm getting `no such table` error? - Why I'm getting `no such table` error?
@@ -516,7 +505,7 @@ For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/
Note that if the last database connection in the pool closes, the in-memory database is deleted. Make sure the [max idle connection limit](https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns) is > 0, and the [connection lifetime](https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime) is infinite. Note that if the last database connection in the pool closes, the in-memory database is deleted. Make sure the [max idle connection limit](https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns) is > 0, and the [connection lifetime](https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime) is infinite.
For more information see: For more information see
* [#204](https://github.com/mattn/go-sqlite3/issues/204) * [#204](https://github.com/mattn/go-sqlite3/issues/204)
* [#511](https://github.com/mattn/go-sqlite3/issues/511) * [#511](https://github.com/mattn/go-sqlite3/issues/511)
* https://www.sqlite.org/sharedcache.html#shared_cache_and_in_memory_databases * https://www.sqlite.org/sharedcache.html#shared_cache_and_in_memory_databases
@@ -526,20 +515,20 @@ For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/
OS X limits OS-wide to not have more than 1000 files open simultaneously by default. OS X limits OS-wide to not have more than 1000 files open simultaneously by default.
For more information, see [#289](https://github.com/mattn/go-sqlite3/issues/289) For more information see [#289](https://github.com/mattn/go-sqlite3/issues/289)
- Trying to execute a `.` (dot) command throws an error. - Trying to execute a `.` (dot) command throws an error.
Error: `Error: near ".": syntax error` Error: `Error: near ".": syntax error`
Dot command are part of SQLite3 CLI, not of this library. Dot command are part of SQLite3 CLI not of this library.
You need to implement the feature or call the sqlite3 cli. You need to implement the feature or call the sqlite3 cli.
More information see [#305](https://github.com/mattn/go-sqlite3/issues/305). More information see [#305](https://github.com/mattn/go-sqlite3/issues/305)
- Error: `database is locked` - Error: `database is locked`
When you get a database is locked, please use the following options. When you get a database is locked. Please use the following options.
Add to DSN: `cache=shared` Add to DSN: `cache=shared`
@@ -548,24 +537,24 @@ For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/
db, err := sql.Open("sqlite3", "file:locked.sqlite?cache=shared") db, err := sql.Open("sqlite3", "file:locked.sqlite?cache=shared")
``` ```
Next, please set the database connections of the SQL package to 1: Second please set the database connections of the SQL package to 1.
```go ```go
db.SetMaxOpenConns(1) db.SetMaxOpenConns(1)
``` ```
For more information, see [#209](https://github.com/mattn/go-sqlite3/issues/209). More information see [#209](https://github.com/mattn/go-sqlite3/issues/209)
## Contributors ## Contributors
### Code Contributors ### Code Contributors
This project exists thanks to all the people who [[contribute](CONTRIBUTING.md)]. This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/mattn/go-sqlite3/graphs/contributors"><img src="https://opencollective.com/mattn-go-sqlite3/contributors.svg?width=890&button=false" /></a> <a href="https://github.com/mattn/go-sqlite3/graphs/contributors"><img src="https://opencollective.com/mattn-go-sqlite3/contributors.svg?width=890&button=false" /></a>
### Financial Contributors ### Financial Contributors
Become a financial contributor and help us sustain our community. [[Contribute here](https://opencollective.com/mattn-go-sqlite3/contribute)]. Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/mattn-go-sqlite3/contribute)]
#### Individuals #### Individuals

View File

@@ -7,7 +7,7 @@ package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif

View File

@@ -12,7 +12,7 @@ package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
@@ -100,13 +100,13 @@ func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op int, db
// Use handles to avoid passing Go pointers to C. // Use handles to avoid passing Go pointers to C.
type handleVal struct { type handleVal struct {
db *SQLiteConn db *SQLiteConn
val any val interface{}
} }
var handleLock sync.Mutex var handleLock sync.Mutex
var handleVals = make(map[unsafe.Pointer]handleVal) var handleVals = make(map[unsafe.Pointer]handleVal)
func newHandle(db *SQLiteConn, v any) unsafe.Pointer { func newHandle(db *SQLiteConn, v interface{}) unsafe.Pointer {
handleLock.Lock() handleLock.Lock()
defer handleLock.Unlock() defer handleLock.Unlock()
val := handleVal{db: db, val: v} val := handleVal{db: db, val: v}
@@ -124,7 +124,7 @@ func lookupHandleVal(handle unsafe.Pointer) handleVal {
return handleVals[handle] return handleVals[handle]
} }
func lookupHandle(handle unsafe.Pointer) any { func lookupHandle(handle unsafe.Pointer) interface{} {
return lookupHandleVal(handle).val return lookupHandleVal(handle).val
} }
@@ -238,7 +238,7 @@ func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
switch typ.Kind() { switch typ.Kind() {
case reflect.Interface: case reflect.Interface:
if typ.NumMethod() != 0 { if typ.NumMethod() != 0 {
return nil, errors.New("the only supported interface type is any") return nil, errors.New("the only supported interface type is interface{}")
} }
return callbackArgGeneric, nil return callbackArgGeneric, nil
case reflect.Slice: case reflect.Slice:
@@ -353,20 +353,6 @@ func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error {
return nil return nil
} }
func callbackRetGeneric(ctx *C.sqlite3_context, v reflect.Value) error {
if v.IsNil() {
C.sqlite3_result_null(ctx)
return nil
}
cb, err := callbackRet(v.Elem().Type())
if err != nil {
return err
}
return cb(ctx, v.Elem())
}
func callbackRet(typ reflect.Type) (callbackRetConverter, error) { func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
switch typ.Kind() { switch typ.Kind() {
case reflect.Interface: case reflect.Interface:
@@ -374,11 +360,6 @@ func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
if typ.Implements(errorInterface) { if typ.Implements(errorInterface) {
return callbackRetNil, nil return callbackRetNil, nil
} }
if typ.NumMethod() == 0 {
return callbackRetGeneric, nil
}
fallthrough fallthrough
case reflect.Slice: case reflect.Slice:
if typ.Elem().Kind() != reflect.Uint8 { if typ.Elem().Kind() != reflect.Uint8 {

View File

@@ -23,7 +23,7 @@ var errNilPtr = errors.New("destination pointer is nil") // embedded in descript
// convertAssign copies to dest the value in src, converting it if possible. // convertAssign copies to dest the value in src, converting it if possible.
// An error is returned if the copy would result in loss of information. // An error is returned if the copy would result in loss of information.
// dest should be a pointer type. // dest should be a pointer type.
func convertAssign(dest, src any) error { func convertAssign(dest, src interface{}) error {
// Common cases, without reflect. // Common cases, without reflect.
switch s := src.(type) { switch s := src.(type) {
case string: case string:
@@ -55,7 +55,7 @@ func convertAssign(dest, src any) error {
} }
*d = string(s) *d = string(s)
return nil return nil
case *any: case *interface{}:
if d == nil { if d == nil {
return errNilPtr return errNilPtr
} }
@@ -97,7 +97,7 @@ func convertAssign(dest, src any) error {
} }
case nil: case nil:
switch d := dest.(type) { switch d := dest.(type) {
case *any: case *interface{}:
if d == nil { if d == nil {
return errNilPtr return errNilPtr
} }
@@ -149,7 +149,7 @@ func convertAssign(dest, src any) error {
*d = bv.(bool) *d = bv.(bool)
} }
return err return err
case *any: case *interface{}:
*d = src *d = src
return nil return nil
} }
@@ -256,7 +256,7 @@ func cloneBytes(b []byte) []byte {
return c return c
} }
func asString(src any) string { func asString(src interface{}) string {
switch v := src.(type) { switch v := src.(type) {
case string: case string:
return v return v

View File

@@ -5,63 +5,63 @@ This works as a driver for database/sql.
Installation Installation
go get github.com/mattn/go-sqlite3 go get github.com/mattn/go-sqlite3
# Supported Types Supported Types
Currently, go-sqlite3 supports the following data types. Currently, go-sqlite3 supports the following data types.
+------------------------------+ +------------------------------+
|go | sqlite3 | |go | sqlite3 |
|----------|-------------------| |----------|-------------------|
|nil | null | |nil | null |
|int | integer | |int | integer |
|int64 | integer | |int64 | integer |
|float64 | float | |float64 | float |
|bool | integer | |bool | integer |
|[]byte | blob | |[]byte | blob |
|string | text | |string | text |
|time.Time | timestamp/datetime| |time.Time | timestamp/datetime|
+------------------------------+ +------------------------------+
# SQLite3 Extension SQLite3 Extension
You can write your own extension module for sqlite3. For example, below is an You can write your own extension module for sqlite3. For example, below is an
extension for a Regexp matcher operation. extension for a Regexp matcher operation.
#include <pcre.h> #include <pcre.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <sqlite3ext.h> #include <sqlite3ext.h>
SQLITE_EXTENSION_INIT1 SQLITE_EXTENSION_INIT1
static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) { static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) {
if (argc >= 2) { if (argc >= 2) {
const char *target = (const char *)sqlite3_value_text(argv[1]); const char *target = (const char *)sqlite3_value_text(argv[1]);
const char *pattern = (const char *)sqlite3_value_text(argv[0]); const char *pattern = (const char *)sqlite3_value_text(argv[0]);
const char* errstr = NULL; const char* errstr = NULL;
int erroff = 0; int erroff = 0;
int vec[500]; int vec[500];
int n, rc; int n, rc;
pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL); pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL);
rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500); rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500);
if (rc <= 0) { if (rc <= 0) {
sqlite3_result_error(context, errstr, 0); sqlite3_result_error(context, errstr, 0);
return; return;
} }
sqlite3_result_int(context, 1); sqlite3_result_int(context, 1);
} }
} }
#ifdef _WIN32 #ifdef _WIN32
__declspec(dllexport) __declspec(dllexport)
#endif #endif
int sqlite3_extension_init(sqlite3 *db, char **errmsg, int sqlite3_extension_init(sqlite3 *db, char **errmsg,
const sqlite3_api_routines *api) { const sqlite3_api_routines *api) {
SQLITE_EXTENSION_INIT2(api); SQLITE_EXTENSION_INIT2(api);
return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8,
(void*)db, regexp_func, NULL, NULL); (void*)db, regexp_func, NULL, NULL);
} }
It needs to be built as a so/dll shared library. And you need to register It needs to be built as a so/dll shared library. And you need to register
the extension module like below. the extension module like below.
@@ -77,7 +77,7 @@ Then, you can use this extension.
rows, err := db.Query("select text from mytable where name regexp '^golang'") rows, err := db.Query("select text from mytable where name regexp '^golang'")
# Connection Hook Connection Hook
You can hook and inject your code when the connection is established by setting You can hook and inject your code when the connection is established by setting
ConnectHook to get the SQLiteConn. ConnectHook to get the SQLiteConn.
@@ -95,13 +95,13 @@ You can also use database/sql.Conn.Raw (Go >= 1.13):
conn, err := db.Conn(context.Background()) conn, err := db.Conn(context.Background())
// if err != nil { ... } // if err != nil { ... }
defer conn.Close() defer conn.Close()
err = conn.Raw(func (driverConn any) error { err = conn.Raw(func (driverConn interface{}) error {
sqliteConn := driverConn.(*sqlite3.SQLiteConn) sqliteConn := driverConn.(*sqlite3.SQLiteConn)
// ... use sqliteConn // ... use sqliteConn
}) })
// if err != nil { ... } // if err != nil { ... }
# Go SQlite3 Extensions Go SQlite3 Extensions
If you want to register Go functions as SQLite extension functions If you want to register Go functions as SQLite extension functions
you can make a custom driver by calling RegisterFunction from you can make a custom driver by calling RegisterFunction from
@@ -130,5 +130,6 @@ You can then use the custom driver by passing its name to sql.Open.
} }
See the documentation of RegisterFunc for more details. See the documentation of RegisterFunc for more details.
*/ */
package sqlite3 package sqlite3

View File

@@ -7,7 +7,7 @@ package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build cgo
// +build cgo // +build cgo
package sqlite3 package sqlite3
@@ -21,10 +20,9 @@ package sqlite3
#cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 #cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1
#cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT #cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
#cgo CFLAGS: -Wno-deprecated-declarations #cgo CFLAGS: -Wno-deprecated-declarations
#cgo openbsd CFLAGS: -I/usr/local/include #cgo linux,!android CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
#cgo openbsd LDFLAGS: -L/usr/local/lib
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
@@ -47,18 +45,6 @@ package sqlite3
# define SQLITE_DETERMINISTIC 0 # define SQLITE_DETERMINISTIC 0
#endif #endif
#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
# undef USE_PREAD
# undef USE_PWRITE
# define USE_PREAD64 1
# define USE_PWRITE64 1
#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
# undef USE_PREAD
# undef USE_PWRITE
# define USE_PREAD64 1
# define USE_PWRITE64 1
#endif
static int static int
_sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) { _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
#ifdef SQLITE_OPEN_URI #ifdef SQLITE_OPEN_URI
@@ -245,14 +231,8 @@ const (
columnTimestamp string = "timestamp" columnTimestamp string = "timestamp"
) )
// This variable can be replaced with -ldflags like below:
// go build -ldflags="-X 'github.com/mattn/go-sqlite3.driverName=my-sqlite3'"
var driverName = "sqlite3"
func init() { func init() {
if driverName != "" { sql.Register("sqlite3", &SQLiteDriver{})
sql.Register(driverName, &SQLiteDriver{})
}
} }
// Version returns SQLite library version information. // Version returns SQLite library version information.
@@ -308,51 +288,6 @@ const (
/*SQLITE_RECURSIVE = C.SQLITE_RECURSIVE*/ /*SQLITE_RECURSIVE = C.SQLITE_RECURSIVE*/
) )
// Standard File Control Opcodes
// See: https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html
const (
SQLITE_FCNTL_LOCKSTATE = int(1)
SQLITE_FCNTL_GET_LOCKPROXYFILE = int(2)
SQLITE_FCNTL_SET_LOCKPROXYFILE = int(3)
SQLITE_FCNTL_LAST_ERRNO = int(4)
SQLITE_FCNTL_SIZE_HINT = int(5)
SQLITE_FCNTL_CHUNK_SIZE = int(6)
SQLITE_FCNTL_FILE_POINTER = int(7)
SQLITE_FCNTL_SYNC_OMITTED = int(8)
SQLITE_FCNTL_WIN32_AV_RETRY = int(9)
SQLITE_FCNTL_PERSIST_WAL = int(10)
SQLITE_FCNTL_OVERWRITE = int(11)
SQLITE_FCNTL_VFSNAME = int(12)
SQLITE_FCNTL_POWERSAFE_OVERWRITE = int(13)
SQLITE_FCNTL_PRAGMA = int(14)
SQLITE_FCNTL_BUSYHANDLER = int(15)
SQLITE_FCNTL_TEMPFILENAME = int(16)
SQLITE_FCNTL_MMAP_SIZE = int(18)
SQLITE_FCNTL_TRACE = int(19)
SQLITE_FCNTL_HAS_MOVED = int(20)
SQLITE_FCNTL_SYNC = int(21)
SQLITE_FCNTL_COMMIT_PHASETWO = int(22)
SQLITE_FCNTL_WIN32_SET_HANDLE = int(23)
SQLITE_FCNTL_WAL_BLOCK = int(24)
SQLITE_FCNTL_ZIPVFS = int(25)
SQLITE_FCNTL_RBU = int(26)
SQLITE_FCNTL_VFS_POINTER = int(27)
SQLITE_FCNTL_JOURNAL_POINTER = int(28)
SQLITE_FCNTL_WIN32_GET_HANDLE = int(29)
SQLITE_FCNTL_PDB = int(30)
SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = int(31)
SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = int(32)
SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = int(33)
SQLITE_FCNTL_LOCK_TIMEOUT = int(34)
SQLITE_FCNTL_DATA_VERSION = int(35)
SQLITE_FCNTL_SIZE_LIMIT = int(36)
SQLITE_FCNTL_CKPT_DONE = int(37)
SQLITE_FCNTL_RESERVE_BYTES = int(38)
SQLITE_FCNTL_CKPT_START = int(39)
SQLITE_FCNTL_EXTERNAL_READER = int(40)
SQLITE_FCNTL_CKSM_FILE = int(41)
)
// SQLiteDriver implements driver.Driver. // SQLiteDriver implements driver.Driver.
type SQLiteDriver struct { type SQLiteDriver struct {
Extensions []string Extensions []string
@@ -505,12 +440,10 @@ func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
// Commit transaction. // Commit transaction.
func (tx *SQLiteTx) Commit() error { func (tx *SQLiteTx) Commit() error {
_, err := tx.c.exec(context.Background(), "COMMIT", nil) _, err := tx.c.exec(context.Background(), "COMMIT", nil)
if err != nil { if err != nil && err.(Error).Code == C.SQLITE_BUSY {
// sqlite3 may leave the transaction open in this scenario. // sqlite3 will leave the transaction open in this scenario.
// However, database/sql considers the transaction complete once we // However, database/sql considers the transaction complete once we
// return from Commit() - we must clean up to honour its semantics. // return from Commit() - we must clean up to honour its semantics.
// We don't know if the ROLLBACK is strictly necessary, but according
// to sqlite's docs, there is no harm in calling ROLLBACK unnecessarily.
tx.c.exec(context.Background(), "ROLLBACK", nil) tx.c.exec(context.Background(), "ROLLBACK", nil)
} }
return err return err
@@ -607,9 +540,10 @@ func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, strin
// RegisterFunc makes a Go function available as a SQLite function. // RegisterFunc makes a Go function available as a SQLite function.
// //
// The Go function can have arguments of the following types: any // The Go function can have arguments of the following types: any
// numeric type except complex, bool, []byte, string and any. // numeric type except complex, bool, []byte, string and
// any arguments are given the direct translation of the SQLite data type: // interface{}. interface{} arguments are given the direct translation
// int64 for INTEGER, float64 for FLOAT, []byte for BLOB, string for TEXT. // of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
// []byte for BLOB, string for TEXT.
// //
// The function can additionally be variadic, as long as the type of // The function can additionally be variadic, as long as the type of
// the variadic argument is one of the above. // the variadic argument is one of the above.
@@ -619,7 +553,7 @@ func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, strin
// optimizations in its queries. // optimizations in its queries.
// //
// See _example/go_custom_funcs for a detailed example. // See _example/go_custom_funcs for a detailed example.
func (c *SQLiteConn) RegisterFunc(name string, impl any, pure bool) error { func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
var fi functionInfo var fi functionInfo
fi.f = reflect.ValueOf(impl) fi.f = reflect.ValueOf(impl)
t := fi.f.Type() t := fi.f.Type()
@@ -701,7 +635,7 @@ func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTe
// return an error in addition to their other return values. // return an error in addition to their other return values.
// //
// See _example/go_custom_funcs for a detailed example. // See _example/go_custom_funcs for a detailed example.
func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error { func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
var ai aggInfo var ai aggInfo
ai.constructor = reflect.ValueOf(impl) ai.constructor = reflect.ValueOf(impl)
t := ai.constructor.Type() t := ai.constructor.Type()
@@ -847,9 +781,9 @@ func lastError(db *C.sqlite3) error {
// Exec implements Execer. // Exec implements Execer.
func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) { func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
list := make([]driver.NamedValue, len(args)) list := make([]namedValue, len(args))
for i, v := range args { for i, v := range args {
list[i] = driver.NamedValue{ list[i] = namedValue{
Ordinal: i + 1, Ordinal: i + 1,
Value: v, Value: v,
} }
@@ -857,7 +791,7 @@ func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, err
return c.exec(context.Background(), query, list) return c.exec(context.Background(), query, list)
} }
func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
start := 0 start := 0
for { for {
s, err := c.prepare(ctx, query) s, err := c.prepare(ctx, query)
@@ -866,7 +800,7 @@ func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.Named
} }
var res driver.Result var res driver.Result
if s.(*SQLiteStmt).s != nil { if s.(*SQLiteStmt).s != nil {
stmtArgs := make([]driver.NamedValue, 0, len(args)) stmtArgs := make([]namedValue, 0, len(args))
na := s.NumInput() na := s.NumInput()
if len(args)-start < na { if len(args)-start < na {
s.Close() s.Close()
@@ -875,17 +809,15 @@ func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.Named
// consume the number of arguments used in the current // consume the number of arguments used in the current
// statement and append all named arguments not // statement and append all named arguments not
// contained therein // contained therein
if len(args[start:start+na]) > 0 { stmtArgs = append(stmtArgs, args[start:start+na]...)
stmtArgs = append(stmtArgs, args[start:start+na]...) for i := range args {
for i := range args { if (i < start || i >= na) && args[i].Name != "" {
if (i < start || i >= na) && args[i].Name != "" { stmtArgs = append(stmtArgs, args[i])
stmtArgs = append(stmtArgs, args[i])
}
}
for i := range stmtArgs {
stmtArgs[i].Ordinal = i + 1
} }
} }
for i := range stmtArgs {
stmtArgs[i].Ordinal = i + 1
}
res, err = s.(*SQLiteStmt).exec(ctx, stmtArgs) res, err = s.(*SQLiteStmt).exec(ctx, stmtArgs)
if err != nil && err != driver.ErrSkip { if err != nil && err != driver.ErrSkip {
s.Close() s.Close()
@@ -896,21 +828,23 @@ func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.Named
tail := s.(*SQLiteStmt).t tail := s.(*SQLiteStmt).t
s.Close() s.Close()
if tail == "" { if tail == "" {
if res == nil {
// https://github.com/mattn/go-sqlite3/issues/963
res = &SQLiteResult{0, 0}
}
return res, nil return res, nil
} }
query = tail query = tail
} }
} }
type namedValue struct {
Name string
Ordinal int
Value driver.Value
}
// Query implements Queryer. // Query implements Queryer.
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
list := make([]driver.NamedValue, len(args)) list := make([]namedValue, len(args))
for i, v := range args { for i, v := range args {
list[i] = driver.NamedValue{ list[i] = namedValue{
Ordinal: i + 1, Ordinal: i + 1,
Value: v, Value: v,
} }
@@ -918,10 +852,10 @@ func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, erro
return c.query(context.Background(), query, list) return c.query(context.Background(), query, list)
} }
func (c *SQLiteConn) query(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
start := 0 start := 0
for { for {
stmtArgs := make([]driver.NamedValue, 0, len(args)) stmtArgs := make([]namedValue, 0, len(args))
s, err := c.prepare(ctx, query) s, err := c.prepare(ctx, query)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -977,104 +911,103 @@ func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
// The argument is may be either in parentheses or it may be separated from // The argument is may be either in parentheses or it may be separated from
// the pragma name by an equal sign. The two syntaxes yield identical results. // the pragma name by an equal sign. The two syntaxes yield identical results.
// In many pragmas, the argument is a boolean. The boolean can be one of: // In many pragmas, the argument is a boolean. The boolean can be one of:
// // 1 yes true on
// 1 yes true on // 0 no false off
// 0 no false off
// //
// You can specify a DSN string using a URI as the filename. // You can specify a DSN string using a URI as the filename.
// test.db
// file:test.db?cache=shared&mode=memory
// :memory:
// file::memory:
// //
// test.db // mode
// file:test.db?cache=shared&mode=memory // Access mode of the database.
// :memory: // https://www.sqlite.org/c3ref/open.html
// file::memory: // Values:
// - ro
// - rw
// - rwc
// - memory
// //
// mode // cache
// Access mode of the database. // SQLite Shared-Cache Mode
// https://www.sqlite.org/c3ref/open.html // https://www.sqlite.org/sharedcache.html
// Values: // Values:
// - ro // - shared
// - rw // - private
// - rwc
// - memory
// //
// cache // immutable=Boolean
// SQLite Shared-Cache Mode // The immutable parameter is a boolean query parameter that indicates
// https://www.sqlite.org/sharedcache.html // that the database file is stored on read-only media. When immutable is set,
// Values: // SQLite assumes that the database file cannot be changed,
// - shared // even by a process with higher privilege,
// - private // and so the database is opened read-only and all locking and change detection is disabled.
// // Caution: Setting the immutable property on a database file that
// immutable=Boolean // does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
// The immutable parameter is a boolean query parameter that indicates
// that the database file is stored on read-only media. When immutable is set,
// SQLite assumes that the database file cannot be changed,
// even by a process with higher privilege,
// and so the database is opened read-only and all locking and change detection is disabled.
// Caution: Setting the immutable property on a database file that
// does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
// //
// go-sqlite3 adds the following query parameters to those used by SQLite: // go-sqlite3 adds the following query parameters to those used by SQLite:
// _loc=XXX
// Specify location of time format. It's possible to specify "auto".
// //
// _loc=XXX // _mutex=XXX
// Specify location of time format. It's possible to specify "auto". // Specify mutex mode. XXX can be "no", "full".
// //
// _mutex=XXX // _txlock=XXX
// Specify mutex mode. XXX can be "no", "full". // Specify locking behavior for transactions. XXX can be "immediate",
// "deferred", "exclusive".
// //
// _txlock=XXX // _auto_vacuum=X | _vacuum=X
// Specify locking behavior for transactions. XXX can be "immediate", // 0 | none - Auto Vacuum disabled
// "deferred", "exclusive". // 1 | full - Auto Vacuum FULL
// 2 | incremental - Auto Vacuum Incremental
// //
// _auto_vacuum=X | _vacuum=X // _busy_timeout=XXX"| _timeout=XXX
// 0 | none - Auto Vacuum disabled // Specify value for sqlite3_busy_timeout.
// 1 | full - Auto Vacuum FULL
// 2 | incremental - Auto Vacuum Incremental
// //
// _busy_timeout=XXX"| _timeout=XXX // _case_sensitive_like=Boolean | _cslike=Boolean
// Specify value for sqlite3_busy_timeout. // https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
// Default or disabled the LIKE operation is case-insensitive.
// When enabling this options behaviour of LIKE will become case-sensitive.
// //
// _case_sensitive_like=Boolean | _cslike=Boolean // _defer_foreign_keys=Boolean | _defer_fk=Boolean
// https://www.sqlite.org/pragma.html#pragma_case_sensitive_like // Defer Foreign Keys until outermost transaction is committed.
// Default or disabled the LIKE operation is case-insensitive.
// When enabling this options behaviour of LIKE will become case-sensitive.
// //
// _defer_foreign_keys=Boolean | _defer_fk=Boolean // _foreign_keys=Boolean | _fk=Boolean
// Defer Foreign Keys until outermost transaction is committed. // Enable or disable enforcement of foreign keys.
// //
// _foreign_keys=Boolean | _fk=Boolean // _ignore_check_constraints=Boolean
// Enable or disable enforcement of foreign keys. // This pragma enables or disables the enforcement of CHECK constraints.
// The default setting is off, meaning that CHECK constraints are enforced by default.
// //
// _ignore_check_constraints=Boolean // _journal_mode=MODE | _journal=MODE
// This pragma enables or disables the enforcement of CHECK constraints. // Set journal mode for the databases associated with the current connection.
// The default setting is off, meaning that CHECK constraints are enforced by default. // https://www.sqlite.org/pragma.html#pragma_journal_mode
// //
// _journal_mode=MODE | _journal=MODE // _locking_mode=X | _locking=X
// Set journal mode for the databases associated with the current connection. // Sets the database connection locking-mode.
// https://www.sqlite.org/pragma.html#pragma_journal_mode // The locking-mode is either NORMAL or EXCLUSIVE.
// https://www.sqlite.org/pragma.html#pragma_locking_mode
// //
// _locking_mode=X | _locking=X // _query_only=Boolean
// Sets the database connection locking-mode. // The query_only pragma prevents all changes to database files when enabled.
// The locking-mode is either NORMAL or EXCLUSIVE.
// https://www.sqlite.org/pragma.html#pragma_locking_mode
// //
// _query_only=Boolean // _recursive_triggers=Boolean | _rt=Boolean
// The query_only pragma prevents all changes to database files when enabled. // Enable or disable recursive triggers.
// //
// _recursive_triggers=Boolean | _rt=Boolean // _secure_delete=Boolean|FAST
// Enable or disable recursive triggers. // When secure_delete is on, SQLite overwrites deleted content with zeros.
// https://www.sqlite.org/pragma.html#pragma_secure_delete
// //
// _secure_delete=Boolean|FAST // _synchronous=X | _sync=X
// When secure_delete is on, SQLite overwrites deleted content with zeros. // Change the setting of the "synchronous" flag.
// https://www.sqlite.org/pragma.html#pragma_secure_delete // https://www.sqlite.org/pragma.html#pragma_synchronous
//
// _writable_schema=Boolean
// When this pragma is on, the SQLITE_MASTER tables in which database
// can be changed using ordinary UPDATE, INSERT, and DELETE statements.
// Warning: misuse of this pragma can easily result in a corrupt database file.
// //
// _synchronous=X | _sync=X
// Change the setting of the "synchronous" flag.
// https://www.sqlite.org/pragma.html#pragma_synchronous
// //
// _writable_schema=Boolean
// When this pragma is on, the SQLITE_MASTER tables in which database
// can be changed using ordinary UPDATE, INSERT, and DELETE statements.
// Warning: misuse of this pragma can easily result in a corrupt database file.
func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) { func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
if C.sqlite3_threadsafe() == 0 { if C.sqlite3_threadsafe() == 0 {
return nil, errors.New("sqlite library was not compiled for thread-safe operation") return nil, errors.New("sqlite library was not compiled for thread-safe operation")
@@ -1476,6 +1409,12 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
return nil, errors.New("sqlite succeeded without returning a database") return nil, errors.New("sqlite succeeded without returning a database")
} }
rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
if rv != C.SQLITE_OK {
C.sqlite3_close_v2(db)
return nil, Error{Code: ErrNo(rv)}
}
exec := func(s string) error { exec := func(s string) error {
cs := C.CString(s) cs := C.CString(s)
rv := C.sqlite3_exec(db, cs, nil, nil, nil) rv := C.sqlite3_exec(db, cs, nil, nil, nil)
@@ -1486,12 +1425,6 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
return nil return nil
} }
// Busy timeout
if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
// USER AUTHENTICATION // USER AUTHENTICATION
// //
// User Authentication is always performed even when // User Authentication is always performed even when
@@ -1679,7 +1612,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
} }
} }
// Foreign Keys // Forgein Keys
if foreignKeys > -1 { if foreignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil { if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
C.sqlite3_close_v2(db) C.sqlite3_close_v2(db)
@@ -1867,31 +1800,6 @@ func (c *SQLiteConn) SetLimit(id int, newVal int) int {
return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal))) return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
} }
// SetFileControlInt invokes the xFileControl method on a given database. The
// dbName is the name of the database. It will default to "main" if left blank.
// The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument
// and return code are both opcode-specific. Please see the SQLite documentation.
//
// This method is not thread-safe as the returned error code can be changed by
// another call if invoked concurrently.
//
// See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
if dbName == "" {
dbName = "main"
}
cDBName := C.CString(dbName)
defer C.free(unsafe.Pointer(cDBName))
cArg := C.int(arg)
rv := C.sqlite3_file_control(c.db, cDBName, C.int(op), unsafe.Pointer(&cArg))
if rv != C.SQLITE_OK {
return c.lastError()
}
return nil
}
// Close the statement. // Close the statement.
func (s *SQLiteStmt) Close() error { func (s *SQLiteStmt) Close() error {
s.mu.Lock() s.mu.Lock()
@@ -1908,7 +1816,6 @@ func (s *SQLiteStmt) Close() error {
if rv != C.SQLITE_OK { if rv != C.SQLITE_OK {
return s.c.lastError() return s.c.lastError()
} }
s.c = nil
runtime.SetFinalizer(s, nil) runtime.SetFinalizer(s, nil)
return nil return nil
} }
@@ -1920,7 +1827,7 @@ func (s *SQLiteStmt) NumInput() int {
var placeHolder = []byte{0} var placeHolder = []byte{0}
func (s *SQLiteStmt) bind(args []driver.NamedValue) error { func (s *SQLiteStmt) bind(args []namedValue) error {
rv := C.sqlite3_reset(s.s) rv := C.sqlite3_reset(s.s)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
return s.c.lastError() return s.c.lastError()
@@ -1990,9 +1897,9 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
// Query the statement with arguments. Return records. // Query the statement with arguments. Return records.
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
list := make([]driver.NamedValue, len(args)) list := make([]namedValue, len(args))
for i, v := range args { for i, v := range args {
list[i] = driver.NamedValue{ list[i] = namedValue{
Ordinal: i + 1, Ordinal: i + 1,
Value: v, Value: v,
} }
@@ -2000,7 +1907,7 @@ func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
return s.query(context.Background(), list) return s.query(context.Background(), list)
} }
func (s *SQLiteStmt) query(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
if err := s.bind(args); err != nil { if err := s.bind(args); err != nil {
return nil, err return nil, err
} }
@@ -2014,7 +1921,6 @@ func (s *SQLiteStmt) query(ctx context.Context, args []driver.NamedValue) (drive
closed: false, closed: false,
ctx: ctx, ctx: ctx,
} }
runtime.SetFinalizer(rows, (*SQLiteRows).Close)
return rows, nil return rows, nil
} }
@@ -2031,9 +1937,9 @@ func (r *SQLiteResult) RowsAffected() (int64, error) {
// Exec execute the statement with arguments. Return result object. // Exec execute the statement with arguments. Return result object.
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
list := make([]driver.NamedValue, len(args)) list := make([]namedValue, len(args))
for i, v := range args { for i, v := range args {
list[i] = driver.NamedValue{ list[i] = namedValue{
Ordinal: i + 1, Ordinal: i + 1,
Value: v, Value: v,
} }
@@ -2050,7 +1956,7 @@ func isInterruptErr(err error) bool {
} }
// exec executes a query that doesn't return rows. Attempts to honor context timeout. // exec executes a query that doesn't return rows. Attempts to honor context timeout.
func (s *SQLiteStmt) exec(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
if ctx.Done() == nil { if ctx.Done() == nil {
return s.execSync(args) return s.execSync(args)
} }
@@ -2060,7 +1966,6 @@ func (s *SQLiteStmt) exec(ctx context.Context, args []driver.NamedValue) (driver
err error err error
} }
resultCh := make(chan result) resultCh := make(chan result)
defer close(resultCh)
go func() { go func() {
r, err := s.execSync(args) r, err := s.execSync(args)
resultCh <- result{r, err} resultCh <- result{r, err}
@@ -2083,7 +1988,7 @@ func (s *SQLiteStmt) exec(ctx context.Context, args []driver.NamedValue) (driver
return rv.r, rv.err return rv.r, rv.err
} }
func (s *SQLiteStmt) execSync(args []driver.NamedValue) (driver.Result, error) { func (s *SQLiteStmt) execSync(args []namedValue) (driver.Result, error) {
if err := s.bind(args); err != nil { if err := s.bind(args); err != nil {
C.sqlite3_reset(s.s) C.sqlite3_reset(s.s)
C.sqlite3_clear_bindings(s.s) C.sqlite3_clear_bindings(s.s)
@@ -2127,8 +2032,6 @@ func (rc *SQLiteRows) Close() error {
return rc.s.c.lastError() return rc.s.c.lastError()
} }
rc.s.mu.Unlock() rc.s.mu.Unlock()
rc.s = nil
runtime.SetFinalizer(rc, nil)
return nil return nil
} }
@@ -2175,7 +2078,6 @@ func (rc *SQLiteRows) Next(dest []driver.Value) error {
return rc.nextSyncLocked(dest) return rc.nextSyncLocked(dest)
} }
resultCh := make(chan error) resultCh := make(chan error)
defer close(resultCh)
go func() { go func() {
resultCh <- rc.nextSyncLocked(dest) resultCh <- rc.nextSyncLocked(dest)
}() }()

View File

@@ -8,7 +8,7 @@ package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif

View File

@@ -50,15 +50,15 @@ import (
// perhaps using a cryptographic hash function like SHA1. // perhaps using a cryptographic hash function like SHA1.
// CryptEncoderSHA1 encodes a password with SHA1 // CryptEncoderSHA1 encodes a password with SHA1
func CryptEncoderSHA1(pass []byte, hash any) []byte { func CryptEncoderSHA1(pass []byte, hash interface{}) []byte {
h := sha1.Sum(pass) h := sha1.Sum(pass)
return h[:] return h[:]
} }
// CryptEncoderSSHA1 encodes a password with SHA1 with the // CryptEncoderSSHA1 encodes a password with SHA1 with the
// configured salt. // configured salt.
func CryptEncoderSSHA1(salt string) func(pass []byte, hash any) []byte { func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash any) []byte { return func(pass []byte, hash interface{}) []byte {
s := []byte(salt) s := []byte(salt)
p := append(pass, s...) p := append(pass, s...)
h := sha1.Sum(p) h := sha1.Sum(p)
@@ -67,15 +67,15 @@ func CryptEncoderSSHA1(salt string) func(pass []byte, hash any) []byte {
} }
// CryptEncoderSHA256 encodes a password with SHA256 // CryptEncoderSHA256 encodes a password with SHA256
func CryptEncoderSHA256(pass []byte, hash any) []byte { func CryptEncoderSHA256(pass []byte, hash interface{}) []byte {
h := sha256.Sum256(pass) h := sha256.Sum256(pass)
return h[:] return h[:]
} }
// CryptEncoderSSHA256 encodes a password with SHA256 // CryptEncoderSSHA256 encodes a password with SHA256
// with the configured salt // with the configured salt
func CryptEncoderSSHA256(salt string) func(pass []byte, hash any) []byte { func CryptEncoderSSHA256(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash any) []byte { return func(pass []byte, hash interface{}) []byte {
s := []byte(salt) s := []byte(salt)
p := append(pass, s...) p := append(pass, s...)
h := sha256.Sum256(p) h := sha256.Sum256(p)
@@ -84,15 +84,15 @@ func CryptEncoderSSHA256(salt string) func(pass []byte, hash any) []byte {
} }
// CryptEncoderSHA384 encodes a password with SHA384 // CryptEncoderSHA384 encodes a password with SHA384
func CryptEncoderSHA384(pass []byte, hash any) []byte { func CryptEncoderSHA384(pass []byte, hash interface{}) []byte {
h := sha512.Sum384(pass) h := sha512.Sum384(pass)
return h[:] return h[:]
} }
// CryptEncoderSSHA384 encodes a password with SHA384 // CryptEncoderSSHA384 encodes a password with SHA384
// with the configured salt // with the configured salt
func CryptEncoderSSHA384(salt string) func(pass []byte, hash any) []byte { func CryptEncoderSSHA384(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash any) []byte { return func(pass []byte, hash interface{}) []byte {
s := []byte(salt) s := []byte(salt)
p := append(pass, s...) p := append(pass, s...)
h := sha512.Sum384(p) h := sha512.Sum384(p)
@@ -101,15 +101,15 @@ func CryptEncoderSSHA384(salt string) func(pass []byte, hash any) []byte {
} }
// CryptEncoderSHA512 encodes a password with SHA512 // CryptEncoderSHA512 encodes a password with SHA512
func CryptEncoderSHA512(pass []byte, hash any) []byte { func CryptEncoderSHA512(pass []byte, hash interface{}) []byte {
h := sha512.Sum512(pass) h := sha512.Sum512(pass)
return h[:] return h[:]
} }
// CryptEncoderSSHA512 encodes a password with SHA512 // CryptEncoderSSHA512 encodes a password with SHA512
// with the configured salt // with the configured salt
func CryptEncoderSSHA512(salt string) func(pass []byte, hash any) []byte { func CryptEncoderSSHA512(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash any) []byte { return func(pass []byte, hash interface{}) []byte {
s := []byte(salt) s := []byte(salt)
p := append(pass, s...) p := append(pass, s...)
h := sha512.Sum512(p) h := sha512.Sum512(p)

View File

@@ -3,8 +3,8 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build cgo && go1.8 // +build cgo
// +build cgo,go1.8 // +build go1.8
package sqlite3 package sqlite3
@@ -25,12 +25,20 @@ func (c *SQLiteConn) Ping(ctx context.Context) error {
// QueryContext implement QueryerContext. // QueryContext implement QueryerContext.
func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
return c.query(ctx, query, args) list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.query(ctx, query, list)
} }
// ExecContext implement ExecerContext. // ExecContext implement ExecerContext.
func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
return c.exec(ctx, query, args) list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.exec(ctx, query, list)
} }
// PrepareContext implement ConnPrepareContext. // PrepareContext implement ConnPrepareContext.
@@ -45,10 +53,18 @@ func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver
// QueryContext implement QueryerContext. // QueryContext implement QueryerContext.
func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
return s.query(ctx, args) list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.query(ctx, list)
} }
// ExecContext implement ExecerContext. // ExecContext implement ExecerContext.
func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
return s.exec(ctx, args) list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.exec(ctx, list)
} }

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build libsqlite3
// +build libsqlite3 // +build libsqlite3
package sqlite3 package sqlite3
@@ -11,13 +10,10 @@ package sqlite3
/* /*
#cgo CFLAGS: -DUSE_LIBSQLITE3 #cgo CFLAGS: -DUSE_LIBSQLITE3
#cgo linux LDFLAGS: -lsqlite3 #cgo linux LDFLAGS: -lsqlite3
#cgo darwin,amd64 LDFLAGS: -L/usr/local/opt/sqlite/lib -lsqlite3 #cgo darwin LDFLAGS: -L/usr/local/opt/sqlite/lib -lsqlite3
#cgo darwin,amd64 CFLAGS: -I/usr/local/opt/sqlite/include #cgo darwin CFLAGS: -I/usr/local/opt/sqlite/include
#cgo darwin,arm64 LDFLAGS: -L/opt/homebrew/opt/sqlite/lib -lsqlite3
#cgo darwin,arm64 CFLAGS: -I/opt/homebrew/opt/sqlite/include
#cgo openbsd LDFLAGS: -lsqlite3 #cgo openbsd LDFLAGS: -lsqlite3
#cgo solaris LDFLAGS: -lsqlite3 #cgo solaris LDFLAGS: -lsqlite3
#cgo windows LDFLAGS: -lsqlite3 #cgo windows LDFLAGS: -lsqlite3
#cgo zos LDFLAGS: -lsqlite3
*/ */
import "C" import "C"

View File

@@ -3,14 +3,13 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !sqlite_omit_load_extension
// +build !sqlite_omit_load_extension // +build !sqlite_omit_load_extension
package sqlite3 package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_omit_load_extension
// +build sqlite_omit_load_extension // +build sqlite_omit_load_extension
package sqlite3 package sqlite3

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_allow_uri_authority
// +build sqlite_allow_uri_authority // +build sqlite_allow_uri_authority
package sqlite3 package sqlite3

View File

@@ -4,8 +4,8 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !windows && sqlite_app_armor // +build !windows
// +build !windows,sqlite_app_armor // +build sqlite_app_armor
package sqlite3 package sqlite3

View File

@@ -1,4 +1,3 @@
//go:build sqlite_column_metadata
// +build sqlite_column_metadata // +build sqlite_column_metadata
package sqlite3 package sqlite3

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_foreign_keys
// +build sqlite_foreign_keys // +build sqlite_foreign_keys
package sqlite3 package sqlite3

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_fts5 || fts5
// +build sqlite_fts5 fts5 // +build sqlite_fts5 fts5
package sqlite3 package sqlite3

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_icu || icu
// +build sqlite_icu icu // +build sqlite_icu icu
package sqlite3 package sqlite3
@@ -11,10 +10,8 @@ package sqlite3
/* /*
#cgo LDFLAGS: -licuuc -licui18n #cgo LDFLAGS: -licuuc -licui18n
#cgo CFLAGS: -DSQLITE_ENABLE_ICU #cgo CFLAGS: -DSQLITE_ENABLE_ICU
#cgo darwin,amd64 CFLAGS: -I/usr/local/opt/icu4c/include #cgo darwin CFLAGS: -I/usr/local/opt/icu4c/include
#cgo darwin,amd64 LDFLAGS: -L/usr/local/opt/icu4c/lib #cgo darwin LDFLAGS: -L/usr/local/opt/icu4c/lib
#cgo darwin,arm64 CFLAGS: -I/opt/homebrew/opt/icu4c/include
#cgo darwin,arm64 LDFLAGS: -L/opt/homebrew/opt/icu4c/lib
#cgo openbsd LDFLAGS: -lsqlite3 #cgo openbsd LDFLAGS: -lsqlite3
*/ */
import "C" import "C"

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_introspect
// +build sqlite_introspect // +build sqlite_introspect
package sqlite3 package sqlite3

View File

@@ -0,0 +1,13 @@
// Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build sqlite_json sqlite_json1 json1
package sqlite3
/*
#cgo CFLAGS: -DSQLITE_ENABLE_JSON1
*/
import "C"

View File

@@ -1,15 +0,0 @@
// Copyright (C) 2022 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build sqlite_math_functions
// +build sqlite_math_functions
package sqlite3
/*
#cgo CFLAGS: -DSQLITE_ENABLE_MATH_FUNCTIONS
#cgo LDFLAGS: -lm
*/
import "C"

View File

@@ -1,15 +0,0 @@
// Copyright (C) 2022 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build sqlite_os_trace
// +build sqlite_os_trace
package sqlite3
/*
#cgo CFLAGS: -DSQLITE_FORCE_OS_TRACE=1
#cgo CFLAGS: -DSQLITE_DEBUG_OS_TRACE=1
*/
import "C"

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build cgo
// +build cgo // +build cgo
package sqlite3 package sqlite3

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_preupdate_hook
// +build sqlite_preupdate_hook // +build sqlite_preupdate_hook
package sqlite3 package sqlite3
@@ -14,7 +13,7 @@ package sqlite3
#cgo LDFLAGS: -lm #cgo LDFLAGS: -lm
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
@@ -34,7 +33,7 @@ import (
// The callback is passed a SQLitePreUpdateData struct with the data for // The callback is passed a SQLitePreUpdateData struct with the data for
// the update, as well as methods for fetching copies of impacted data. // the update, as well as methods for fetching copies of impacted data.
// //
// If there is an existing preupdate hook for this connection, it will be // If there is an existing update hook for this connection, it will be
// removed. If callback is nil the existing hook (if any) will be removed // removed. If callback is nil the existing hook (if any) will be removed
// without creating a new one. // without creating a new one.
func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) { func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) {
@@ -55,10 +54,10 @@ func (d *SQLitePreUpdateData) Count() int {
return int(C.sqlite3_preupdate_count(d.Conn.db)) return int(C.sqlite3_preupdate_count(d.Conn.db))
} }
func (d *SQLitePreUpdateData) row(dest []any, new bool) error { func (d *SQLitePreUpdateData) row(dest []interface{}, new bool) error {
for i := 0; i < d.Count() && i < len(dest); i++ { for i := 0; i < d.Count() && i < len(dest); i++ {
var val *C.sqlite3_value var val *C.sqlite3_value
var src any var src interface{}
// Initially I tried making this just a function pointer argument, but // Initially I tried making this just a function pointer argument, but
// it's absurdly complicated to pass C function pointers. // it's absurdly complicated to pass C function pointers.
@@ -96,7 +95,7 @@ func (d *SQLitePreUpdateData) row(dest []any, new bool) error {
// Old populates dest with the row data to be replaced. This works similar to // Old populates dest with the row data to be replaced. This works similar to
// database/sql's Rows.Scan() // database/sql's Rows.Scan()
func (d *SQLitePreUpdateData) Old(dest ...any) error { func (d *SQLitePreUpdateData) Old(dest ...interface{}) error {
if d.Op == SQLITE_INSERT { if d.Op == SQLITE_INSERT {
return errors.New("There is no old row for INSERT operations") return errors.New("There is no old row for INSERT operations")
} }
@@ -105,7 +104,7 @@ func (d *SQLitePreUpdateData) Old(dest ...any) error {
// New populates dest with the replacement row data. This works similar to // New populates dest with the replacement row data. This works similar to
// database/sql's Rows.Scan() // database/sql's Rows.Scan()
func (d *SQLitePreUpdateData) New(dest ...any) error { func (d *SQLitePreUpdateData) New(dest ...interface{}) error {
if d.Op == SQLITE_DELETE { if d.Op == SQLITE_DELETE {
return errors.New("There is no new row for DELETE operations") return errors.New("There is no new row for DELETE operations")
} }

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !sqlite_preupdate_hook && cgo
// +build !sqlite_preupdate_hook,cgo // +build !sqlite_preupdate_hook,cgo
package sqlite3 package sqlite3
@@ -14,7 +13,7 @@ package sqlite3
// The callback is passed a SQLitePreUpdateData struct with the data for // The callback is passed a SQLitePreUpdateData struct with the data for
// the update, as well as methods for fetching copies of impacted data. // the update, as well as methods for fetching copies of impacted data.
// //
// If there is an existing preupdate hook for this connection, it will be // If there is an existing update hook for this connection, it will be
// removed. If callback is nil the existing hook (if any) will be removed // removed. If callback is nil the existing hook (if any) will be removed
// without creating a new one. // without creating a new one.
func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) { func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) {

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_secure_delete
// +build sqlite_secure_delete // +build sqlite_secure_delete
package sqlite3 package sqlite3

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_secure_delete_fast
// +build sqlite_secure_delete_fast // +build sqlite_secure_delete_fast
package sqlite3 package sqlite3

View File

@@ -1,83 +0,0 @@
//go:build !libsqlite3 || sqlite_serialize
// +build !libsqlite3 sqlite_serialize
package sqlite3
/*
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
#include <stdlib.h>
#include <stdint.h>
*/
import "C"
import (
"fmt"
"math"
"reflect"
"unsafe"
)
// Serialize returns a byte slice that is a serialization of the database.
//
// See https://www.sqlite.org/c3ref/serialize.html
func (c *SQLiteConn) Serialize(schema string) ([]byte, error) {
if schema == "" {
schema = "main"
}
var zSchema *C.char
zSchema = C.CString(schema)
defer C.free(unsafe.Pointer(zSchema))
var sz C.sqlite3_int64
ptr := C.sqlite3_serialize(c.db, zSchema, &sz, 0)
if ptr == nil {
return nil, fmt.Errorf("serialize failed")
}
defer C.sqlite3_free(unsafe.Pointer(ptr))
if sz > C.sqlite3_int64(math.MaxInt) {
return nil, fmt.Errorf("serialized database is too large (%d bytes)", sz)
}
cBuf := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(ptr)),
Len: int(sz),
Cap: int(sz),
}))
res := make([]byte, int(sz))
copy(res, cBuf)
return res, nil
}
// Deserialize causes the connection to disconnect from the current database and
// then re-open as an in-memory database based on the contents of the byte slice.
//
// See https://www.sqlite.org/c3ref/deserialize.html
func (c *SQLiteConn) Deserialize(b []byte, schema string) error {
if schema == "" {
schema = "main"
}
var zSchema *C.char
zSchema = C.CString(schema)
defer C.free(unsafe.Pointer(zSchema))
tmpBuf := (*C.uchar)(C.sqlite3_malloc64(C.sqlite3_uint64(len(b))))
cBuf := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(tmpBuf)),
Len: len(b),
Cap: len(b),
}))
copy(cBuf, b)
rc := C.sqlite3_deserialize(c.db, zSchema, tmpBuf, C.sqlite3_int64(len(b)),
C.sqlite3_int64(len(b)), C.SQLITE_DESERIALIZE_FREEONCLOSE)
if rc != C.SQLITE_OK {
return fmt.Errorf("deserialize failed with return %v", rc)
}
return nil
}

View File

@@ -1,21 +0,0 @@
//go:build libsqlite3 && !sqlite_serialize
// +build libsqlite3,!sqlite_serialize
package sqlite3
import (
"errors"
)
/*
#cgo CFLAGS: -DSQLITE_OMIT_DESERIALIZE
*/
import "C"
func (c *SQLiteConn) Serialize(schema string) ([]byte, error) {
return nil, errors.New("sqlite3: Serialize requires the sqlite_serialize build tag when using the libsqlite3 build tag")
}
func (c *SQLiteConn) Deserialize(b []byte, schema string) error {
return errors.New("sqlite3: Deserialize requires the sqlite_serialize build tag when using the libsqlite3 build tag")
}

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_stat4
// +build sqlite_stat4 // +build sqlite_stat4
package sqlite3 package sqlite3

View File

@@ -5,7 +5,7 @@
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
#include <stdio.h> #include <stdio.h>
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
extern int unlock_notify_wait(sqlite3 *db); extern int unlock_notify_wait(sqlite3 *db);

View File

@@ -3,8 +3,8 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build cgo && sqlite_unlock_notify // +build cgo
// +build cgo,sqlite_unlock_notify // +build sqlite_unlock_notify
package sqlite3 package sqlite3
@@ -12,7 +12,7 @@ package sqlite3
#cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY #cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY
#include <stdlib.h> #include <stdlib.h>
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
extern void unlock_notify_callback(void *arg, int argc); extern void unlock_notify_callback(void *arg, int argc);
*/ */

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_userauth
// +build sqlite_userauth // +build sqlite_userauth
package sqlite3 package sqlite3
@@ -12,7 +11,7 @@ package sqlite3
#cgo CFLAGS: -DSQLITE_USER_AUTHENTICATION #cgo CFLAGS: -DSQLITE_USER_AUTHENTICATION
#cgo LDFLAGS: -lm #cgo LDFLAGS: -lm
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
@@ -80,13 +79,13 @@ var (
// If a database contains the SQLITE_USER table, then the // If a database contains the SQLITE_USER table, then the
// call to Authenticate must be invoked with an // call to Authenticate must be invoked with an
// appropriate username and password prior to enable read and write // appropriate username and password prior to enable read and write
// access to the database. //access to the database.
// //
// Return SQLITE_OK on success or SQLITE_ERROR if the username/password // Return SQLITE_OK on success or SQLITE_ERROR if the username/password
// combination is incorrect or unknown. // combination is incorrect or unknown.
// //
// If the SQLITE_USER table is not present in the database file, then // If the SQLITE_USER table is not present in the database file, then
// this interface is a harmless no-op returning SQLITE_OK. // this interface is a harmless no-op returnning SQLITE_OK.
func (c *SQLiteConn) Authenticate(username, password string) error { func (c *SQLiteConn) Authenticate(username, password string) error {
rv := c.authenticate(username, password) rv := c.authenticate(username, password)
switch rv { switch rv {
@@ -104,10 +103,9 @@ func (c *SQLiteConn) Authenticate(username, password string) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authenticate(username, password string) int { func (c *SQLiteConn) authenticate(username, password string) int {
// Allocate C Variables // Allocate C Variables
cuser := C.CString(username) cuser := C.CString(username)
@@ -157,10 +155,9 @@ func (c *SQLiteConn) AuthUserAdd(username, password string, admin bool) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserAdd(username, password string, admin int) int { func (c *SQLiteConn) authUserAdd(username, password string, admin int) int {
// Allocate C Variables // Allocate C Variables
cuser := C.CString(username) cuser := C.CString(username)
@@ -210,10 +207,9 @@ func (c *SQLiteConn) AuthUserChange(username, password string, admin bool) error
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserChange(username, password string, admin int) int { func (c *SQLiteConn) authUserChange(username, password string, admin int) int {
// Allocate C Variables // Allocate C Variables
cuser := C.CString(username) cuser := C.CString(username)
@@ -253,10 +249,9 @@ func (c *SQLiteConn) AuthUserDelete(username string) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserDelete(username string) int { func (c *SQLiteConn) authUserDelete(username string) int {
// Allocate C Variables // Allocate C Variables
cuser := C.CString(username) cuser := C.CString(username)
@@ -285,9 +280,8 @@ func (c *SQLiteConn) AuthEnabled() (exists bool) {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // 0 - Disabled
// 0 - Disabled // 1 - Enabled
// 1 - Enabled
func (c *SQLiteConn) authEnabled() int { func (c *SQLiteConn) authEnabled() int {
return int(C._sqlite3_auth_enabled(c.db)) return int(C._sqlite3_auth_enabled(c.db))
} }

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !sqlite_userauth
// +build !sqlite_userauth // +build !sqlite_userauth
package sqlite3 package sqlite3
@@ -18,7 +17,7 @@ import (
// If a database contains the SQLITE_USER table, then the // If a database contains the SQLITE_USER table, then the
// call to Authenticate must be invoked with an // call to Authenticate must be invoked with an
// appropriate username and password prior to enable read and write // appropriate username and password prior to enable read and write
// access to the database. //access to the database.
// //
// Return SQLITE_OK on success or SQLITE_ERROR if the username/password // Return SQLITE_OK on success or SQLITE_ERROR if the username/password
// combination is incorrect or unknown. // combination is incorrect or unknown.
@@ -35,10 +34,9 @@ func (c *SQLiteConn) Authenticate(username, password string) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authenticate(username, password string) int { func (c *SQLiteConn) authenticate(username, password string) int {
// NOOP // NOOP
return 0 return 0
@@ -67,10 +65,9 @@ func (c *SQLiteConn) AuthUserAdd(username, password string, admin bool) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserAdd(username, password string, admin int) int { func (c *SQLiteConn) authUserAdd(username, password string, admin int) int {
// NOOP // NOOP
return 0 return 0
@@ -99,10 +96,9 @@ func (c *SQLiteConn) AuthUserChange(username, password string, admin bool) error
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserChange(username, password string, admin int) int { func (c *SQLiteConn) authUserChange(username, password string, admin int) int {
// NOOP // NOOP
return 0 return 0
@@ -126,10 +122,9 @@ func (c *SQLiteConn) AuthUserDelete(username string) error {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // C.SQLITE_OK (0)
// C.SQLITE_OK (0) // C.SQLITE_ERROR (1)
// C.SQLITE_ERROR (1) // C.SQLITE_AUTH (23)
// C.SQLITE_AUTH (23)
func (c *SQLiteConn) authUserDelete(username string) int { func (c *SQLiteConn) authUserDelete(username string) int {
// NOOP // NOOP
return 0 return 0
@@ -147,9 +142,8 @@ func (c *SQLiteConn) AuthEnabled() (exists bool) {
// It is however exported for usage within SQL by the user. // It is however exported for usage within SQL by the user.
// //
// Returns: // Returns:
// // 0 - Disabled
// 0 - Disabled // 1 - Enabled
// 1 - Enabled
func (c *SQLiteConn) authEnabled() int { func (c *SQLiteConn) authEnabled() int {
// NOOP // NOOP
return 0 return 0

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_vacuum_full
// +build sqlite_vacuum_full // +build sqlite_vacuum_full
package sqlite3 package sqlite3

View File

@@ -4,7 +4,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_vacuum_incr
// +build sqlite_vacuum_incr // +build sqlite_vacuum_incr
package sqlite3 package sqlite3

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_vtable || vtable
// +build sqlite_vtable vtable // +build sqlite_vtable vtable
package sqlite3 package sqlite3
@@ -20,7 +19,7 @@ package sqlite3
#cgo CFLAGS: -Wno-deprecated-declarations #cgo CFLAGS: -Wno-deprecated-declarations
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
@@ -473,21 +472,10 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
} }
info.idxNum = C.int(res.IdxNum) info.idxNum = C.int(res.IdxNum)
info.idxStr = (*C.char)(C.sqlite3_malloc(C.int(len(res.IdxStr) + 1))) idxStr := C.CString(res.IdxStr)
if info.idxStr == nil { defer C.free(unsafe.Pointer(idxStr))
// C.malloc and C.CString ordinarily do this for you. See https://golang.org/cmd/cgo/ info.idxStr = idxStr
panic("out of memory") info.needToFreeIdxStr = C.int(0)
}
info.needToFreeIdxStr = C.int(1)
idxStr := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(info.idxStr)),
Len: len(res.IdxStr) + 1,
Cap: len(res.IdxStr) + 1,
}))
copy(idxStr, res.IdxStr)
idxStr[len(idxStr)-1] = 0 // null-terminated string
if res.AlreadyOrdered { if res.AlreadyOrdered {
info.orderByConsumed = C.int(1) info.orderByConsumed = C.int(1)
} }
@@ -517,7 +505,7 @@ func goMDestroy(pClientData unsafe.Pointer) {
func goVFilter(pCursor unsafe.Pointer, idxNum C.int, idxName *C.char, argc C.int, argv **C.sqlite3_value) *C.char { func goVFilter(pCursor unsafe.Pointer, idxNum C.int, idxName *C.char, argc C.int, argv **C.sqlite3_value) *C.char {
vtc := lookupHandle(pCursor).(*sqliteVTabCursor) vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc] args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
vals := make([]any, 0, argc) vals := make([]interface{}, 0, argc)
for _, v := range args { for _, v := range args {
conv, err := callbackArgGeneric(v) conv, err := callbackArgGeneric(v)
if err != nil { if err != nil {
@@ -589,7 +577,7 @@ func goVUpdate(pVTab unsafe.Pointer, argc C.int, argv **C.sqlite3_value, pRowid
if v, ok := vt.vTab.(VTabUpdater); ok { if v, ok := vt.vTab.(VTabUpdater); ok {
// convert argv // convert argv
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc] args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
vals := make([]any, 0, argc) vals := make([]interface{}, 0, argc)
for _, v := range args { for _, v := range args {
conv, err := callbackArgGeneric(v) conv, err := callbackArgGeneric(v)
if err != nil { if err != nil {
@@ -663,9 +651,9 @@ type VTab interface {
// deleted. // deleted.
// See: https://sqlite.org/vtab.html#xupdate // See: https://sqlite.org/vtab.html#xupdate
type VTabUpdater interface { type VTabUpdater interface {
Delete(any) error Delete(interface{}) error
Insert(any, []any) (int64, error) Insert(interface{}, []interface{}) (int64, error)
Update(any, []any) error Update(interface{}, []interface{}) error
} }
// VTabCursor describes cursors that point into the virtual table and are used // VTabCursor describes cursors that point into the virtual table and are used
@@ -674,7 +662,7 @@ type VTabCursor interface {
// http://sqlite.org/vtab.html#xclose // http://sqlite.org/vtab.html#xclose
Close() error Close() error
// http://sqlite.org/vtab.html#xfilter // http://sqlite.org/vtab.html#xfilter
Filter(idxNum int, idxStr string, vals []any) error Filter(idxNum int, idxStr string, vals []interface{}) error
// http://sqlite.org/vtab.html#xnext // http://sqlite.org/vtab.html#xnext
Next() error Next() error
// http://sqlite.org/vtab.html#xeof // http://sqlite.org/vtab.html#xeof

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !windows
// +build !windows // +build !windows
package sqlite3 package sqlite3

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build solaris
// +build solaris // +build solaris
package sqlite3 package sqlite3

View File

@@ -3,14 +3,13 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build sqlite_trace || trace
// +build sqlite_trace trace // +build sqlite_trace trace
package sqlite3 package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif

View File

@@ -1,4 +1,5 @@
// Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
@@ -6,16 +7,15 @@ package sqlite3
/* /*
#ifndef USE_LIBSQLITE3 #ifndef USE_LIBSQLITE3
#include "sqlite3-binding.h" #include <sqlite3-binding.h>
#else #else
#include <sqlite3.h> #include <sqlite3.h>
#endif #endif
*/ */
import "C" import "C"
import ( import (
"database/sql"
"reflect" "reflect"
"strings" "time"
) )
// ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName. // ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName.
@@ -31,78 +31,32 @@ func (rc *SQLiteRows) ColumnTypeLength(index int) (length int64, ok bool) {
func (rc *SQLiteRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { func (rc *SQLiteRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return 0, 0, false return 0, 0, false
} }
*/
// ColumnTypeNullable implement RowsColumnTypeNullable. // ColumnTypeNullable implement RowsColumnTypeNullable.
func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool) { func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool) {
return true, true return false, false
} }
*/
// ColumnTypeScanType implement RowsColumnTypeScanType. // ColumnTypeScanType implement RowsColumnTypeScanType.
func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type { func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type {
//ct := C.sqlite3_column_type(rc.s.s, C.int(i)) // Always returns 5 switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
return scanType(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))) case C.SQLITE_INTEGER:
} switch C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))) {
case "timestamp", "datetime", "date":
const ( return reflect.TypeOf(time.Time{})
SQLITE_INTEGER = iota case "boolean":
SQLITE_TEXT return reflect.TypeOf(false)
SQLITE_BLOB }
SQLITE_REAL return reflect.TypeOf(int64(0))
SQLITE_NUMERIC case C.SQLITE_FLOAT:
SQLITE_TIME return reflect.TypeOf(float64(0))
SQLITE_BOOL case C.SQLITE_BLOB:
SQLITE_NULL return reflect.SliceOf(reflect.TypeOf(byte(0)))
) case C.SQLITE_NULL:
return reflect.TypeOf(nil)
func scanType(cdt string) reflect.Type { case C.SQLITE_TEXT:
t := strings.ToUpper(cdt) return reflect.TypeOf("")
i := databaseTypeConvSqlite(t) }
switch i { return reflect.SliceOf(reflect.TypeOf(byte(0)))
case SQLITE_INTEGER:
return reflect.TypeOf(sql.NullInt64{})
case SQLITE_TEXT:
return reflect.TypeOf(sql.NullString{})
case SQLITE_BLOB:
return reflect.TypeOf(sql.RawBytes{})
case SQLITE_REAL:
return reflect.TypeOf(sql.NullFloat64{})
case SQLITE_NUMERIC:
return reflect.TypeOf(sql.NullFloat64{})
case SQLITE_BOOL:
return reflect.TypeOf(sql.NullBool{})
case SQLITE_TIME:
return reflect.TypeOf(sql.NullTime{})
}
return reflect.TypeOf(new(any))
}
func databaseTypeConvSqlite(t string) int {
if strings.Contains(t, "INT") {
return SQLITE_INTEGER
}
if t == "CLOB" || t == "TEXT" ||
strings.Contains(t, "CHAR") {
return SQLITE_TEXT
}
if t == "BLOB" {
return SQLITE_BLOB
}
if t == "REAL" || t == "FLOAT" ||
strings.Contains(t, "DOUBLE") {
return SQLITE_REAL
}
if t == "DATE" || t == "DATETIME" ||
t == "TIMESTAMP" {
return SQLITE_TIME
}
if t == "NUMERIC" ||
strings.Contains(t, "DECIMAL") {
return SQLITE_NUMERIC
}
if t == "BOOLEAN" {
return SQLITE_BOOL
}
return SQLITE_NULL
} }

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build cgo
// +build cgo // +build cgo
package sqlite3 package sqlite3

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build windows
// +build windows // +build windows
package sqlite3 package sqlite3
@@ -13,6 +12,7 @@ package sqlite3
#cgo CFLAGS: -fno-stack-check #cgo CFLAGS: -fno-stack-check
#cgo CFLAGS: -fno-stack-protector #cgo CFLAGS: -fno-stack-protector
#cgo CFLAGS: -mno-stack-arg-probe #cgo CFLAGS: -mno-stack-arg-probe
#cgo LDFLAGS: -lmingwex -lmingw32
#cgo windows,386 CFLAGS: -D_USE_32BIT_TIME_T #cgo windows,386 CFLAGS: -D_USE_32BIT_TIME_T
*/ */
import "C" import "C"

View File

@@ -19,10 +19,6 @@
#ifndef SQLITE3EXT_H #ifndef SQLITE3EXT_H
#define SQLITE3EXT_H #define SQLITE3EXT_H
#include "sqlite3-binding.h" #include "sqlite3-binding.h"
#ifdef __clang__
#define assert(condition) ((void)0)
#endif
/* /*
** The following structure holds pointers to all of the SQLite API ** The following structure holds pointers to all of the SQLite API
@@ -336,41 +332,12 @@ struct sqlite3_api_routines {
const char *(*filename_journal)(const char*); const char *(*filename_journal)(const char*);
const char *(*filename_wal)(const char*); const char *(*filename_wal)(const char*);
/* Version 3.32.0 and later */ /* Version 3.32.0 and later */
const char *(*create_filename)(const char*,const char*,const char*, char *(*create_filename)(const char*,const char*,const char*,
int,const char**); int,const char**);
void (*free_filename)(const char*); void (*free_filename)(char*);
sqlite3_file *(*database_file_object)(const char*); sqlite3_file *(*database_file_object)(const char*);
/* Version 3.34.0 and later */ /* Version 3.34.0 and later */
int (*txn_state)(sqlite3*,const char*); int (*txn_state)(sqlite3*,const char*);
/* Version 3.36.1 and later */
sqlite3_int64 (*changes64)(sqlite3*);
sqlite3_int64 (*total_changes64)(sqlite3*);
/* Version 3.37.0 and later */
int (*autovacuum_pages)(sqlite3*,
unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
void*, void(*)(void*));
/* Version 3.38.0 and later */
int (*error_offset)(sqlite3*);
int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
int (*vtab_distinct)(sqlite3_index_info*);
int (*vtab_in)(sqlite3_index_info*,int,int);
int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
/* Version 3.39.0 and later */
int (*deserialize)(sqlite3*,const char*,unsigned char*,
sqlite3_int64,sqlite3_int64,unsigned);
unsigned char *(*serialize)(sqlite3*,const char *,sqlite3_int64*,
unsigned int);
const char *(*db_name)(sqlite3*,int);
/* Version 3.40.0 and later */
int (*value_encoding)(sqlite3_value*);
/* Version 3.41.0 and later */
int (*is_interrupted)(sqlite3*);
/* Version 3.43.0 and later */
int (*stmt_explain)(sqlite3_stmt*,int);
/* Version 3.44.0 and later */
void *(*get_clientdata)(sqlite3*,const char*);
int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));
}; };
/* /*
@@ -677,33 +644,6 @@ typedef int (*sqlite3_loadext_entry)(
#define sqlite3_database_file_object sqlite3_api->database_file_object #define sqlite3_database_file_object sqlite3_api->database_file_object
/* Version 3.34.0 and later */ /* Version 3.34.0 and later */
#define sqlite3_txn_state sqlite3_api->txn_state #define sqlite3_txn_state sqlite3_api->txn_state
/* Version 3.36.1 and later */
#define sqlite3_changes64 sqlite3_api->changes64
#define sqlite3_total_changes64 sqlite3_api->total_changes64
/* Version 3.37.0 and later */
#define sqlite3_autovacuum_pages sqlite3_api->autovacuum_pages
/* Version 3.38.0 and later */
#define sqlite3_error_offset sqlite3_api->error_offset
#define sqlite3_vtab_rhs_value sqlite3_api->vtab_rhs_value
#define sqlite3_vtab_distinct sqlite3_api->vtab_distinct
#define sqlite3_vtab_in sqlite3_api->vtab_in
#define sqlite3_vtab_in_first sqlite3_api->vtab_in_first
#define sqlite3_vtab_in_next sqlite3_api->vtab_in_next
/* Version 3.39.0 and later */
#ifndef SQLITE_OMIT_DESERIALIZE
#define sqlite3_deserialize sqlite3_api->deserialize
#define sqlite3_serialize sqlite3_api->serialize
#endif
#define sqlite3_db_name sqlite3_api->db_name
/* Version 3.40.0 and later */
#define sqlite3_value_encoding sqlite3_api->value_encoding
/* Version 3.41.0 and later */
#define sqlite3_is_interrupted sqlite3_api->is_interrupted
/* Version 3.43.0 and later */
#define sqlite3_stmt_explain sqlite3_api->stmt_explain
/* Version 3.44.0 and later */
#define sqlite3_get_clientdata sqlite3_api->get_clientdata
#define sqlite3_set_clientdata sqlite3_api->set_clientdata
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)

View File

@@ -3,7 +3,6 @@
// Use of this source code is governed by an MIT-style // Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !cgo
// +build !cgo // +build !cgo
package sqlite3 package sqlite3
@@ -29,10 +28,10 @@ type (
) )
func (SQLiteDriver) Open(s string) (driver.Conn, error) { return nil, errorMsg } func (SQLiteDriver) Open(s string) (driver.Conn, error) { return nil, errorMsg }
func (c *SQLiteConn) RegisterAggregator(string, any, bool) error { return errorMsg } func (c *SQLiteConn) RegisterAggregator(string, interface{}, bool) error { return errorMsg }
func (c *SQLiteConn) RegisterAuthorizer(func(int, string, string, string) int) {} func (c *SQLiteConn) RegisterAuthorizer(func(int, string, string, string) int) {}
func (c *SQLiteConn) RegisterCollation(string, func(string, string) int) error { return errorMsg } func (c *SQLiteConn) RegisterCollation(string, func(string, string) int) error { return errorMsg }
func (c *SQLiteConn) RegisterCommitHook(func() int) {} func (c *SQLiteConn) RegisterCommitHook(func() int) {}
func (c *SQLiteConn) RegisterFunc(string, any, bool) error { return errorMsg } func (c *SQLiteConn) RegisterFunc(string, interface{}, bool) error { return errorMsg }
func (c *SQLiteConn) RegisterRollbackHook(func()) {} func (c *SQLiteConn) RegisterRollbackHook(func()) {}
func (c *SQLiteConn) RegisterUpdateHook(func(int, string, string, int64)) {} func (c *SQLiteConn) RegisterUpdateHook(func(int, string, string, int64)) {}

File diff suppressed because it is too large Load Diff

View File

@@ -924,7 +924,7 @@ func inBodyIM(p *parser) bool {
p.addElement() p.addElement()
p.im = inFramesetIM p.im = inFramesetIM
return true return true
case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Main, a.Menu, a.Nav, a.Ol, a.P, a.Search, a.Section, a.Summary, a.Ul: case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Main, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
p.popUntil(buttonScope, a.P) p.popUntil(buttonScope, a.P)
p.addElement() p.addElement()
case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6: case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
@@ -1136,7 +1136,7 @@ func inBodyIM(p *parser) bool {
return false return false
} }
return true return true
case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Main, a.Menu, a.Nav, a.Ol, a.Pre, a.Search, a.Section, a.Summary, a.Ul: case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Main, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
p.popUntil(defaultScope, p.tok.DataAtom) p.popUntil(defaultScope, p.tok.DataAtom)
case a.Form: case a.Form:
if p.oe.contains(a.Template) { if p.oe.contains(a.Template) {

View File

@@ -839,22 +839,8 @@ func (z *Tokenizer) readStartTag() TokenType {
if raw { if raw {
z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end])) z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
} }
// Look for a self-closing token (e.g. <br/>). // Look for a self-closing token like "<br/>".
// if z.err == nil && z.buf[z.raw.end-2] == '/' {
// Originally, we did this by just checking that the last character of the
// tag (ignoring the closing bracket) was a solidus (/) character, but this
// is not always accurate.
//
// We need to be careful that we don't misinterpret a non-self-closing tag
// as self-closing, as can happen if the tag contains unquoted attribute
// values (i.e. <p a=/>).
//
// To avoid this, we check that the last non-bracket character of the tag
// (z.raw.end-2) isn't the same character as the last non-quote character of
// the last attribute of the tag (z.pendingAttr[1].end-1), if the tag has
// attributes.
nAttrs := len(z.attr)
if z.err == nil && z.buf[z.raw.end-2] == '/' && (nAttrs == 0 || z.raw.end-2 != z.attr[nAttrs-1][1].end-1) {
return SelfClosingTagToken return SelfClosingTagToken
} }
return StartTagToken return StartTagToken

View File

@@ -43,8 +43,8 @@ type DLL struct {
// LoadDLL loads DLL file into memory. // LoadDLL loads DLL file into memory.
// //
// Warning: using LoadDLL without an absolute path name is subject to // Warning: using LoadDLL without an absolute path name is subject to
// DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL], // DLL preloading attacks. To safely load a system DLL, use LazyDLL
// or use [LoadLibraryEx] directly. // with System set to true, or use LoadLibraryEx directly.
func LoadDLL(name string) (dll *DLL, err error) { func LoadDLL(name string) (dll *DLL, err error) {
namep, err := UTF16PtrFromString(name) namep, err := UTF16PtrFromString(name)
if err != nil { if err != nil {
@@ -271,9 +271,6 @@ func (d *LazyDLL) NewProc(name string) *LazyProc {
} }
// NewLazyDLL creates new LazyDLL associated with DLL file. // NewLazyDLL creates new LazyDLL associated with DLL file.
//
// Warning: using NewLazyDLL without an absolute path name is subject to
// DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL].
func NewLazyDLL(name string) *LazyDLL { func NewLazyDLL(name string) *LazyDLL {
return &LazyDLL{Name: name} return &LazyDLL{Name: name}
} }
@@ -413,3 +410,7 @@ func loadLibraryEx(name string, system bool) (*DLL, error) {
} }
return &DLL{Name: name, Handle: h}, nil return &DLL{Name: name, Handle: h}, nil
} }
type errString string
func (s errString) Error() string { return string(s) }

View File

@@ -59,7 +59,7 @@ func (c CanonType) Parse(s string) (t Tag, err error) {
if changed { if changed {
tt.RemakeString() tt.RemakeString()
} }
return makeTag(tt), nil return makeTag(tt), err
} }
// Compose creates a Tag from individual parts, which may be of type Tag, Base, // Compose creates a Tag from individual parts, which may be of type Tag, Base,

16
vendor/modules.txt vendored
View File

@@ -1,16 +1,16 @@
# github.com/mattn/go-sqlite3 v1.14.24 # github.com/mattn/go-sqlite3 v1.14.7
## explicit; go 1.19 ## explicit; go 1.12
github.com/mattn/go-sqlite3 github.com/mattn/go-sqlite3
# golang.org/x/net v0.38.0 # golang.org/x/net v0.33.0
## explicit; go 1.23.0 ## explicit; go 1.18
golang.org/x/net/html golang.org/x/net/html
golang.org/x/net/html/atom golang.org/x/net/html/atom
golang.org/x/net/html/charset golang.org/x/net/html/charset
# golang.org/x/sys v0.31.0 # golang.org/x/sys v0.28.0
## explicit; go 1.23.0 ## explicit; go 1.18
golang.org/x/sys/windows golang.org/x/sys/windows
# golang.org/x/text v0.23.0 # golang.org/x/text v0.21.0
## explicit; go 1.23.0 ## explicit; go 1.18
golang.org/x/text/encoding golang.org/x/text/encoding
golang.org/x/text/encoding/charmap golang.org/x/text/encoding/charmap
golang.org/x/text/encoding/htmlindex golang.org/x/text/encoding/htmlindex