Giter Club home page Giter Club logo

go-sqlite3's Introduction

go-sqlite3

Go Reference GitHub Actions Financial Contributors on Open Collective codecov Go Report Card

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.

Description

A sqlite3 driver that conforms to the built-in database/sql interface.

Supported Golang version: See .github/workflows/go.yaml.

This package follows the official Golang Release Policy.

Overview

Installation

This package can be installed with the go get command:

go get github.com/mattn/go-sqlite3

go-sqlite3 is cgo package. 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.

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.

API Reference

API documentation can be found here.

Examples can be found under the examples directory.

Connection String

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.

Options are append after the filename of the SQLite database. The database filename and options are separated by an ? (Question Mark). Options should be URL-encoded (see url.QueryEscape).

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.

This library supports DSN options of SQLite itself and provides additional options.

Boolean values can be one of:

  • 0 no false off
  • 1 yes true on
Name Key Value(s) Description
UA - Create _auth - Create User Authentication, for more information see User Authentication
UA - Username _auth_user string Username for User Authentication, for more information see User Authentication
UA - Password _auth_pass string Password for User Authentication, for more information see User Authentication
UA - Crypt _auth_crypt
  • SHA1
  • SSHA1
  • SHA256
  • SSHA256
  • SHA384
  • SSHA384
  • SHA512
  • SSHA512
Password encoder to use for User Authentication, for more information see User Authentication
UA - Salt _auth_salt string Salt to use if the configure password encoder requires a salt, for User Authentication, for more information see User Authentication
Auto Vacuum _auto_vacuum | _vacuum
  • 0 | none
  • 1 | full
  • 2 | incremental
For more information see PRAGMA auto_vacuum
Busy Timeout _busy_timeout | _timeout int Specify value for sqlite3_busy_timeout. For more information see PRAGMA busy_timeout
Case Sensitive LIKE _case_sensitive_like | _cslike boolean For more information see PRAGMA case_sensitive_like
Defer Foreign Keys _defer_foreign_keys | _defer_fk boolean For more information see PRAGMA defer_foreign_keys
Foreign Keys _foreign_keys | _fk boolean For more information see PRAGMA foreign_keys
Ignore CHECK Constraints _ignore_check_constraints boolean For more information see PRAGMA ignore_check_constraints
Immutable immutable boolean For more information see Immutable
Journal Mode _journal_mode | _journal
  • DELETE
  • TRUNCATE
  • PERSIST
  • MEMORY
  • WAL
  • OFF
For more information see PRAGMA journal_mode
Locking Mode _locking_mode | _locking
  • NORMAL
  • EXCLUSIVE
For more information see PRAGMA locking_mode
Mode mode
  • ro
  • rw
  • rwc
  • memory
Access Mode of the database. For more information see SQLite Open
Mutex Locking _mutex
  • no
  • full
Specify mutex mode.
Query Only _query_only boolean For more information see PRAGMA query_only
Recursive Triggers _recursive_triggers | _rt boolean For more information see PRAGMA recursive_triggers
Secure Delete _secure_delete boolean | FAST For more information see PRAGMA secure_delete
Shared-Cache Mode cache
  • shared
  • private
Set cache mode for more information see sqlite.org
Synchronous _synchronous | _sync
  • 0 | OFF
  • 1 | NORMAL
  • 2 | FULL
  • 3 | EXTRA
For more information see PRAGMA synchronous
Time Zone Location _loc auto Specify location of time format.
Transaction Lock _txlock
  • immediate
  • deferred
  • exclusive
Specify locking behavior for transactions.
Writable Schema _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.
Cache Size _cache_size int Maximum cache size; default is 2000K (2M). See PRAGMA cache_size

DSN Examples

file:test.db?cache=shared&mode=memory

Features

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 for more information about build tags / constraints.

Usage

If you wish to build this library with additional extensions / features, use the following command:

go build -tags "<FEATURE>"

For available features, see the extension list. When using multiple build tags, all the different tags should be space delimited.

Example:

go build -tags "icu json1 fts5 secure_delete"

Feature / Extension List

Extension Build Tag Description
Additional Statistics sqlite_stat4 This option adds additional logic to the ANALYZE command and to the query planner that can help SQLite to chose a better query plan under certain situations. The ANALYZE command is enhanced to collect histogram data from all columns of every index and store that data in the sqlite_stat4 table.

The query planner will then use the histogram data to help it make better index choices. The downside of this compile-time option is that it violates the query planner stability guarantee making it more difficult to ensure consistent performance in mass-produced applications.

SQLITE_ENABLE_STAT4 is an enhancement of SQLITE_ENABLE_STAT3. STAT3 only recorded histogram data for the left-most column of each index whereas the STAT4 enhancement records histogram data from all columns of each index.

The SQLITE_ENABLE_STAT3 compile-time option is a no-op and is ignored if the SQLITE_ENABLE_STAT4 compile-time option is used
Allow URI Authority sqlite_allow_uri_authority URI filenames normally throws an error if the authority section is not either empty or "localhost".

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.

App Armor is not available under Windows.
Disable Load Extensions sqlite_omit_load_extension Loading of external extensions is enabled by default.

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.

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.

Each database connection can always turn enforcement of foreign key constraints on and off and run-time using the foreign_keys pragma.

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
Incremental Auto Vacuum sqlite_vacuum_incr Set the default auto vacuum to incremental
Full Text Search Engine sqlite_fts5 When this option is defined in the amalgamation, versions 5 of the full-text search engine (fts5) is added to the build automatically
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.
  • PRAGMA function_list
  • PRAGMA module_list
  • PRAGMA pragma_list
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
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.
Secure Delete sqlite_secure_delete This compile-time option changes the default setting of the secure_delete pragma.

When this option is not used, secure_delete defaults to off. When this option is present, secure_delete defaults to on.

The secure_delete setting causes deleted content to be overwritten with zeros. There is a small performance penalty since additional I/O must occur.

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
Tracing / Debug sqlite_trace Activate trace functions
User Authentication sqlite_userauth SQLite User Authentication see User Authentication for more information.
Virtual Tables sqlite_vtable SQLite Virtual Tables see SQLite Official VTABLE Documentation for more information, and a full example here

Compilation

This package requires the CGO_ENABLED=1 environment 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.

Android

This package can be compiled for android. Compile with:

go build -tags "android"

For more information see #201

ARM

To compile for ARM use the following environment:

env CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \
    CGO_ENABLED=1 GOOS=linux GOARCH=arm GOARM=7 \
    go build -v 

Additional information:

Cross Compile

This library can be cross-compiled.

In some cases you are required to the CC environment variable with the cross compiler.

Cross Compiling from macOS

The simplest way to cross compile from macOS is to use xgo.

Steps:

  • Install musl-cross (brew install FiloSottile/musl-cross/musl-cross).
  • 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".

Please refer to the project's README for further information.

Google Cloud Platform

Building on GCP is not possible because Google Cloud Platform does not allow gcc to be executed.

Please work only with compiled final binaries.

Linux

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.

go build -tags "linux"

If you wish to link directly to libsqlite3 then you can use the libsqlite3 build tag.

go build -tags "libsqlite3 linux"

Alpine

When building in an alpine container run the following command before building:

apk add --update gcc musl-dev

Fedora

sudo yum groupinstall "Development Tools" "Development Libraries"

Ubuntu

sudo apt-get install build-essential

macOS

macOS should have all the tools present to compile this package. If not, install XCode to add all the developers tools.

Required dependency:

brew install sqlite3

For macOS, there is an additional package to install which is required if you wish to build the icu extension.

This additional package can be installed with homebrew:

brew upgrade icu4c

To compile for macOS on x86:

go build -tags "darwin amd64"

To compile for macOS on ARM chips:

go build -tags "darwin arm64"

If you wish to link directly to libsqlite3, use the libsqlite3 build tag:

# x86 
go build -tags "libsqlite3 darwin amd64"
# ARM
go build -tags "libsqlite3 darwin arm64"

Additional information:

Windows

To compile this package on Windows, you must have the gcc compiler installed.

  1. Install a Windows gcc toolchain.
  2. Add the bin folder 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.
  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.

Errors

  • Compile error: can not be used when making a shared object; recompile with -fPIC

    When receiving a compile time error referencing recompile with -FPIC then you are probably using a hardend system.

    You can compile the library on a hardend system with the following command.

    go build -ldflags '-extldflags=-fno-PIC'

    More details see #120

  • Can't build go-sqlite3 on windows 64bit.

    Probably, you are using go 1.0, go1.0 has a problem when it comes to compiling/linking on windows 64bit. See: #27

  • go get github.com/mattn/go-sqlite3 throws compilation error.

    gcc throws: internal compiler error

    Remove the download repository from your disk and try re-install with:

    go install github.com/mattn/go-sqlite3

User Authentication

This package supports the SQLite User Authentication module.

Compile

To use the User authentication module, the package has to be compiled with the tag sqlite_userauth. See Features.

Usage

Create protected database

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:

  • _auth_user
  • _auth_pass

When _auth is present in 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.

Example connection strings:

Create an user authentication database with user admin and password 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:

file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin&_auth_crypt=sha1

Password Encoding

The passwords within the user authentication module of SQLite are encoded with the SQLite function sqlite_cryp. This function uses a ceasar-cypher which is quite insecure. This library provides several additional password encoders which can be configured through the connection string.

The password cypher can be configured with the key _auth_crypt. And if the configured password encoder also requires an salt this can be configured with _auth_salt.

Available Encoders

  • SHA1
  • SSHA1 (Salted SHA1)
  • SHA256
  • SSHA256 (salted SHA256)
  • SHA384
  • SSHA384 (salted SHA384)
  • SHA512
  • SSHA512 (salted SHA512)

Restrictions

Operations on the database regarding user management can only be preformed by an administrator user.

Support

The user authentication supports two kinds of users:

  • administrators
  • regular users

User Management

User management can be done by directly using the *SQLiteConn or by SQL.

SQL

The following sql functions are available for user management:

Function Arguments Description
authenticate username string, password string Will authenticate an user, this is done by the connection; and should not be used manually.
auth_user_add username string, password string, admin int This function will add an user to the database.
if the database is not protected by user authentication it will enable it. Argument admin is an integer identifying if the added user should be an administrator. Only Administrators can add administrators.
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.

These functions will return an integer:

  • 0 (SQLITE_OK)
  • 23 (SQLITE_AUTH) Failed to perform due to authentication or insufficient privileges
Examples
// Autheticate user
// Create Admin User
SELECT auth_user_add('admin2', 'admin2', 1);

// Change password for user
SELECT auth_user_change('user', 'userpassword', 0);

// Delete user
SELECT user_delete('user');

*SQLiteConn

The following functions are available for User authentication from the *SQLiteConn:

Function Description
Authenticate(username, password string) error Authenticate user
AuthUserAdd(username, password string, admin bool) error Add user
AuthUserChange(username, password string, admin bool) error Modify user
AuthUserDelete(username string) error Delete user

Attached database

When using attached databases, SQLite will use the authentication from the main database for the attached database(s).

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.

Spatialite

Spatialite is available as an extension to SQLite, and can be used in combination with this repository. For an example, see shaxbee/go-spatialite.

extension-functions.c from SQLite3 Contrib

extension-functions.c is available as an extension to SQLite, and provides the following functions:

  • Math: acos, asin, atan, atn2, atan2, acosh, asinh, atanh, difference, degrees, radians, cos, sin, tan, cot, cosh, sinh, tanh, coth, exp, log, log10, power, sign, sqrt, square, ceil, floor, pi.
  • String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, replace, reverse, proper, padl, padr, padc, strfilter.
  • Aggregate: stdev, variance, mode, median, lower_quartile, upper_quartile

For an example, see dinedal/go-sqlite3-extension-functions.

FAQ

  • Getting insert error while query is opened.

    You can pass some arguments into the connection string, for example, a URI. See: #39

  • Do you want to cross compile? mingw on Linux or Mac?

    See: #106 See also: http://www.limitlessfx.com/cross-compile-golang-app-for-windows-from-linux.html

  • Want to get time.Time with current locale

    Use _loc=auto in SQLite3 filename schema like file:foo.db?_loc=auto.

  • Can I use this in multiple routines concurrently?

    Yes for readonly. But not for writable. See #50, #51, #209, #274.

  • Why I'm getting no such table error?

    Why is it racy if I use a sql.Open("sqlite3", ":memory:") database?

    Each connection to ":memory:" opens a brand new in-memory sql database, so if the stdlib's sql engine happens to open another connection and you've only specified ":memory:", that connection will see a brand new database. A workaround is to use "file::memory:?cache=shared" (or "file:foobar?mode=memory&cache=shared"). Every connection to this string will point to the same in-memory database.

    Note that if the last database connection in the pool closes, the in-memory database is deleted. Make sure the max idle connection limit is > 0, and the connection lifetime is infinite.

    For more information see:

  • Reading from database with large amount of goroutines fails on OSX.

    OS X limits OS-wide to not have more than 1000 files open simultaneously by default.

    For more information, see #289

  • Trying to execute a . (dot) command throws an error.

    Error: Error: near ".": syntax error Dot command are part of SQLite3 CLI, not of this library.

    You need to implement the feature or call the sqlite3 cli.

    More information see #305.

  • Error: database is locked

    When you get a database is locked, please use the following options.

    Add to DSN: cache=shared

    Example:

    db, err := sql.Open("sqlite3", "file:locked.sqlite?cache=shared")

    Next, please set the database connections of the SQL package to 1:

    db.SetMaxOpenConns(1)

    For more information, see #209.

Contributors

Code Contributors

This project exists thanks to all the people who [contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute here].

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

License

MIT: http://mattn.mit-license.org/2018

sqlite3-binding.c, sqlite3-binding.h, sqlite3ext.h

The -binding suffix was added to avoid build failures under gccgo.

In this repository, those files are an amalgamation of code that was copied from SQLite3. The license of that code is the same as the license of SQLite3.

Author

Yasuhiro Matsumoto (a.k.a mattn)

G.J.R. Timmer

go-sqlite3's People

Contributors

akalin avatar arp242 avatar azavorotnii avatar bytbox avatar catenacyber avatar conorbranagan avatar cookieo9 avatar dajohi avatar danderson avatar egonelbre avatar evanj avatar gholt avatar gimpldo avatar gjrtimmer avatar itizir avatar jander avatar jgallagher avatar joshbuddy avatar kenshaw avatar larsmans avatar mattn avatar mjtrangoni avatar mstetson avatar otoolep avatar rittneje avatar robertknight avatar shaxbee avatar t2y avatar tuxlinuxien avatar zombiezen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-sqlite3's Issues

Scanning *time.Time is broken

My code (which basically scans a *time.Time) is broken with the recent commits:
Scan error on column index 8: unsupported driver -> Scan pair: string -> *time.Time

int32

Is there any particular reason why int32 data type is not supported?

Also, I don't think executing sqlite3_bind_int for go's int type is the correct action in general. On amd64, C int's are usually 32-bit whereas go ints are 64-bit.

Cannot compile package on OSX

All prerequisites are installed with

brew install pkgconfig
brew install sqlite3

a go get github.com/mattn/go-sqlite3 fails with

go get github.com/mattn/go-sqlite3
# github.com/mattn/go-sqlite3
ld: warning: ignoring file /usr/local/Cellar/sqlite/3.7.14.1/lib/libsqlite3.dylib, file was built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (i386): /usr/local/Cellar/sqlite/3.7.14.1/lib/libsqlite3.dylib
Undefined symbols for architecture i386:
  "_sqlite3_bind_blob", referenced from:
      __cgo_2d0307e709cd_Cfunc__sqlite3_bind_blob in sqlite3.cgo2.o
     (maybe you meant: __cgo_2d0307e709cd_Cfunc__sqlite3_bind_blob)
  "_sqlite3_bind_double", referenced from:
      __cgo_2d0307e709cd_Cfunc_sqlite3_bind_double in sqlite3.cgo2.o
     (maybe you meant: __cgo_2d0307e709cd_Cfunc_sqlite3_bind_double)
  "_sqlite3_bind_int", referenced from:
      __cgo_2d0307e709cd_Cfunc_sqlite3_bind_int in sqlite3.cgo2.o
     (maybe you meant: __cgo_2d0307e709cd_Cfunc_sqlite3_bind_int, __cgo_2d0307e709cd_Cfunc_sqlite3_bind_int64 )

...

  "_sqlite3_threadsafe", referenced from:
      __cgo_2d0307e709cd_Cfunc_sqlite3_threadsafe in sqlite3.cgo2.o
     (maybe you meant: __cgo_2d0307e709cd_Cfunc_sqlite3_threadsafe)
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status

System is 10.8.3

armv7 debian: failed to import driver sqlite3

Hello,

I am trying to do sqlite3 on android (architecture armv7) and I have a Debian SID that I bootstrapped from squeeze on Debian Kit APK

This is terrible!

Failure to import database driver, no helpful errors anywhere. Don't even know what logs to paste.

I have libsqlite3-dev and pkg-config installed, I am using programs that interact with database/sql and they all import github.com/mattn/go-sqlite3 as _, none of them provide any hints what might be going wrong at compile time, but I have read that someone had a similar issue on openbsd amd64.

Something is amiss with gccgo?

Have you tried any different architechtures

--Kingdon

Can't build on Raspberry Pi

Back trace:

github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol close
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol access
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol getcwd
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol ftruncate64
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol fcntl
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol read
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol write
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol fchmod
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol unlink
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol mkdir
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol rmdir
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol mmap64
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol munmap
github.com/mattn/go-sqlite3(.data.rel): unexpected R_ARM_ABS32 relocation for dynamic symbol mremap
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for close (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for access (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for getcwd (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for ftruncate64 (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for fcntl (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for read (type 28 rtype 23)
github.com/mattn/go-sqlite3(.data.rel): unhandled relocation for write (type 28 rtype 23)
too many errors

Seems to be a problem with CGO that could (possibly) be fixed in go 1.2. Is there a way around this issue on current version? (1.1.2 linux/arm).

Sqlite3 version is 3.8.0.1 2013-08-29 17:35:01 352362bc01660edfbda08179d60f09e2038a2f49

If you need anything else please let me know

how to build on windows

you say that build sqlite3 with shared library. If it run on windows, it need dll
so I download from
http://sqlite.org/download.html
and try everything...but still cant successful build it
need step-by-step intro
thx
ps:your go-mruby build successful on my win7 with MinGW64. But your go-sqlite3 can't build success.

Access to matchinfo data

Is there a way of accessing the uint32 array returned by matchinfo via go-sqlite3?
I though of using ordinary scan with []uint32, but the type switch in bind() doesn't switch on []uint32, so I thought it would be impossible (at least without using unsafe).

import not seeing sqlite3 (unknown driver)

probably a user issue on my side, but I'm trying to install the freegeoip stuff that uses this and I continually get the error message:
sql: unknown driver "sqlite3" (forgotten import?)

But I've run through every possible thing I could think of (including checking the import) and it just isn't loading or throwing an error.

This is on a fresh ubuntu server 12.04.2 install:
$ uname -a
Linux ubuntu 3.5.0-23-generic #35~precise1-Ubuntu SMP Fri Jan 25 17:13:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
$ go version
go version go1.1.1 linux/amd64

running the example/main.go here I get the same error. Even creating a simple script causes the error:
$ cat test.go
package main

import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)

func main() {
db, err := sql.Open("sqlite3", "./db/ipdb.sqlite")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(db)
}

$ go run test.go
sql: unknown driver "sqlite3" (forgotten import?)

and I've tried to install and reinstall this package numerous times and it's installed, but it is just not being imported or loading at all. I've double checked the db file, permissions, the whole works.

$ ls $GOPATH/src/github.com/mattn/go-sqlite3
example README.mkd sqlite3ext.h sqlite3.go sqlite3.h sqlite3_other.go sqlite3_test.go sqlite3_windows.c sqlite3_windows.go

$ env | grep GO
GOBIN=/home/jay/src/go/bin
GOARCH=386
GOROOT=/home/jay/src/go
GOOS=linux
GOPATH=/home/jay/gopath

any idea where else I can look and things I could try? Is there some other driver package I might be missing?

go get fails with sqlite-3.3.6-5

It appears that this package depends on some features not present in sqlite-3.3.6:

$ sudo go build github.com/mattn/go-sqlite3

github.com/mattn/go-sqlite3

error: 'sqlite3_int64' undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: 'SQLITE_OPEN_READWRITE' undeclared (first use in this function)
error: 'sqlite3_threadsafe' undeclared (first use in this function)
error: 'SQLITE_OPEN_CREATE' undeclared (first use in this function)
error: 'sqlite3_prepare_v2' undeclared (first use in this function)
error: 'SQLITE_OPEN_FULLMUTEX' undeclared (first use in this function)
error: 'sqlite3_next_stmt' undeclared (first use in this function)
$ rpm -q sqlite-devel
sqlite-devel-3.3.6-5
$

Can a minimum required version be specified?

row.Scan fails when in a transaction

When inside a transaction I attempt to insert and then select the row that was just inserted; the row.Scan function fails with a nil pointer.

Here is the test case:
https://gist.github.com/1672440

[signal 0xb code=0x0 addr=0x0 pc=0x2193dec]

goroutine 1 [chan receive]:
testing.RunTests(0x2000, 0x161cc0, 0x200000002, 0x22c5f01, 0x22c5f28, ...)
    /Users/jaz/Sandbox/go/src/pkg/testing/testing.go:330 +0x795
testing.Main(0x2000, 0x161cc0, 0x200000002, 0x16d978, 0x0, ...)
    /Users/jaz/Sandbox/go/src/pkg/testing/testing.go:265 +0x62
main.main()
    /Users/jaz/Dropbox/projects/disco/pkg/txtest/_testmain.go:31 +0x91

goroutine 3 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_column_name(0x2304240, 0x0)
    /Users/jaz/Sandbox/go-libs/go-sqlite3/_obj/_cgo_defun.c:122 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteRows).Columns(0xf84000e060, 0xf8400215a8, 0x22c6d68, 0x18)
    /Users/jaz/Sandbox/go-libs/go-sqlite3/_obj/sqlite3.cgo1.go:-99 +0x8a
database/sql.(*Rows).Next(0xf840028180, 0x2285020, 0x1552e, 0x86a9)
    /Users/jaz/Sandbox/go/src/pkg/database/sql/sql.go:765 +0x81
database/sql.(*Row).Scan(0xf84000e040, 0x22c6e88, 0x100000001, 0x0, 0x0, ...)
    /Users/jaz/Sandbox/go/src/pkg/database/sql/sql.go:869 +0x9c
txtest.TestSqliteScanInTx(0xf840000150, 0x283a81f8)
    /Users/jaz/Dropbox/projects/disco/pkg/txtest/tx_test.go:61 +0x4c0
testing.tRunner(0xf840000150, 0x161cd8, 0x0, 0x0)
    /Users/jaz/Sandbox/go/src/pkg/testing/testing.go:254 +0x5f
created by testing.RunTests
    /Users/jaz/Sandbox/go/src/pkg/testing/testing.go:329 +0x772
gotest: "./6.out" failed: exit status 2
make: *** [test] Error 2

Error installing go-sqlite3 on Ubuntu LTS 12.04

I am getting the following error while installing go-sqlite3:

sudo go get github.com/mattn/go-sqlite3

github.com/mattn/go-sqlite3

sqlite3.go:138[/tmp/go-build724017084/github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:106]: function ends without a return statement
sqlite3.go:161[/tmp/go-build724017084/github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:130]: function ends without a return statement

"go get" fails on tip

After updating Go from 1.0.3 to tip, go-sqlite3 fails to build. I guess they removed a compiler flag.

$ go get github.com/mattn/go-sqlite3
# github.com/mattn/go-sqlite3
/home/robfig/go/pkg/tool/linux_amd64/6c: unknown flag -FVw

Patch for Go issue 4459

Hello,
A patch can be applied to go-sqlite3 to fix issue 4459 (https://code.google.com/p/go/issues/detail?id=4459):

diff --git a/sqlite3.go b/sqlite3.go
index 0a21d23..6070617 100644
--- a/sqlite3.go
+++ b/sqlite3.go
@@ -136,7 +136,7 @@ func (c *SQLiteConn) Close() error {
        }
        rv := C.sqlite3_close(c.db)
        if rv != C.SQLITE_OK {
-               return errors.New("sqlite succeeded without returning a database")
+               return errors.New("error while closing sqlite database connection")
        }
        c.db = nil
        return nil
@@ -170,6 +170,9 @@ func (s *SQLiteStmt) Close() error {
                return nil
        }
        s.closed = true
+       if s.c == nil || s.c.db == nil {
+               return errors.New("sqlite statement with already closed database connection")
+       }
        rv := C.sqlite3_finalize(s.s)
        if rv != C.SQLITE_OK {
                return errors.New(C.GoString(C.sqlite3_errmsg(s.c.db)))

The error messages may be improved...
Regards

gccgo support

The head of sqlite3.go has 'static int ...' C function declarations. Removing the 'static' word makes the package work for gccgo too.

Unexpected sql: no rows in result set

I have a pretty simple function but keep getting

sql: no rows in result set

which I think is a Sqlite error but not entirely sure.

The only odd thing that I'm doing is setting a

var db *sql.DB

As a global variable.

All my other handlers run fine, it is just this select statement that is causing me problems.

func indexHandler(w http.ResponseWriter, r *http.Request) {                         
  println("Hit indexHandler")                                                       

  t, _ := template.ParseFiles("index.html")                                         
  var links []Link                                                                  

  rows, err := db.Query("SELECT id, name, url, hits FROM links")                    
  if err != nil {                                                                   
    fmt.Println(err)                                                                
    return                                                                          
  }                                                                                 

  defer rows.Close()                                                                
  for rows.Next() {                                                                 
    var (                                                                           
      id int                                                                        
      name string                                                                   
      url string                                                                    
      hits int                                                                      
    )                                                                               

    rows.Scan(&id, &name, &url, &hits)                                              

    link := Link{Id: id, Name: name, Url: url, Hits: hits}                          

    links = append(links, link)                                                     
  }                                                                                 
  rows.Close()                                                                      

  t.Execute(w, map[string][]Link { "Links": links, })                                                   
}      

makefile in example can not work on Go1

Some suggestions about the example:

  1. provide example of "select id,name from foo where id = ?"
  2. provide db.Prepare sample
  3. Is defer db.Close() required? (I don't see it on your example code)

No rows returned when there is an invalid date

I had been using go-sqlite3 for storing timestamps for some months but had to store them cast to strings due to the library apparently not having support for Go's Time type. Recently I noticed that the library now supports Go's Time so updated my code to pass the values in as timestamps instead.

After upgrading go-sqlite3 I found my code was not returning any rows for certain queries. I have tracked this down to some dates in the database that are '0000-00-00 00:00:00'. These obviously got into the database when I was passing them via the library as strings but the new go-sqlite3 will not read them (which is fine) but simply returns no rows and no error.

Personally I think this case should cause an error.

go get is failed

  1. [root@localhost ~]# pkg-config --cflags --libs sqlite3
    -lsqlite3
  2. [root@localhost ~]# go get github.com/mattn/go-sqlite3
# cd .; git clone https://github.com/mattn/go-sqlite3 /home/MyProjects/src/github.com/mattn/go-sqlite3
Cloning into /home/MyProjects/src/github.com/mattn/go-sqlite3...
error: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed while accessing https://github.com/mattn/go-sqlite3/info/refs

fatal: HTTP request failed
package github.com/mattn/go-sqlite3: exit status 128

compile warning expected expected ‘const char **’ but argument is of type ‘char **’

go-hg version 1c2e5d6d7660
sqlite3 3.7.10-1
gcc (GCC) 4.6.2 20120120 (prerelease)

go get -x github.com/mattn/go-sqlite3
...
gcc -I . -g -O2 -fPIC -m64 -pthread -I $WORK/github.com/mattn/go-sqlite3/_obj/ -o $WORK/github.com/mattn/go-sqlite3/_obj/sqlite3.cgo2.o -c $WORK/github.com/mattn/go-sqlite3/_obj/sqlite3.cgo2.c
# github.com/mattn/go-sqlite3
sqlite3.go: In function ‘_cgo_fe2086fd4234_Cfunc_sqlite3_prepare_v2’:
sqlite3.go:324:2: warning: passing argument 5 of ‘sqlite3_prepare_v2’ from incompatible pointer type [enabled by default]
/usr/include/sqlite3.h:2924:16: note: expected ‘const char **’ but argument is of type ‘char **’

Cannot insert while select is active (same or different table)

Cannot insert or update while a query is "opened", which is not prohibited by the SQLite api.

Opening the database with SQLITE_OPEN_NOMUTEX or SQLITE_OPEN_PRIVATECACHE does not fix the problem.

This code while always result in golang "could not insert data into dst: database is locked". When one writes the equivalent code in C, the program just works.

I am about lost as to how to fix the problem. This "kind of use" has been supported by SQLite for quite some time now: database is locked.

package main

import (
    "database/sql"
    _ "github.com/mattn/go-sqlite3"
    "log"
)

func main() {

    db, err := sql.Open("sqlite3", "locked.sqlite")
    if err != nil {
        log.Fatalln("could not open database:", err)
    }
    defer db.Close()

    // Drop, create and insert data into the test table
    _, err = db.Exec("DROP TABLE IF EXISTS src;")
    if err != nil {
        log.Fatalln("could not drop table:", err)
    }
    _, err = db.Exec("DROP TABLE IF EXISTS dst;")
    if err != nil {
        log.Fatalln("could not drop table:", err)
    }

    _, err = db.Exec("CREATE TABLE src (id INTEGER NOT NULL PRIMARY KEY, data1 INTEGER, data2 INTEGER);")
    if err != nil {
        log.Fatalln("could not create table:", err)
    }
    _, err = db.Exec("CREATE TABLE dst (id INTEGER, data1 INTEGER, data2 INTEGER);")
    if err != nil {
        log.Fatalln("could not create table:", err)
    }

    for i := 0; i < 100; i++ {
        _, err = db.Exec("INSERT INTO src (id, data1, data2) VALUES (?, ?, ?);", i, 100 + i, 1000 + i)
        if err != nil {
            log.Fatalln("could not insert into table:", err)
        }
    }

    rows, err := db.Query("SELECT id, data1, data2 FROM src;")
    if err != nil {
        log.Fatalln("could not select data:", err)
    }
    defer rows.Close()

    insert, err := db.Prepare("INSERT INTO dst (id, data1, data2) VALUES (?, ?, ?);")
    if err != nil {
        log.Fatalln("could not prepare statement:", err)
    }
    defer insert.Close()

    for rows.Next() {
        var id, data1, data2 int64

        err = rows.Scan(&id, &data1, &data2)
        if err != nil {
            log.Fatalln("could not scan row:", err)
        }

        _, err = insert.Exec(id, data1, data2)
        if err != nil {
            log.Fatalln("could not insert data into dst:", err)
        }
    }
    insert.Close()
    rows.Close()

    return
}

go get still fails with sqlite-3.3.6-5

The fix for #54 appears to not have fixed the issue completely:

$ go build github.com/mattn/go-sqlite3

github.com/mattn/go-sqlite3

error: 'sqlite3_prepare_v2' undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: 'sqlite3_int64' undeclared (first use in this function)
error: 'sqlite3_threadsafe' undeclared (first use in this function)
error: 'SQLITE_OPEN_CREATE' undeclared (first use in this function)
error: 'sqlite3_next_stmt' undeclared (first use in this function)
$ cat /etc/redhat-release
CentOS release 5.5 (Final)
$ rpm -qa | grep sqlite
sqlite-3.3.6-5
sqlite-devel-3.3.6-5
$

Driver is not supporting Scan string -> *time.Time

Driver is not supporting Scan string -> *time.Time

The test: http://play.golang.org/p/gOE9OlxghQ

sql: Scan error on column index 1: unsupported driver -> Scan pair: string -> *time.Time


In the discussion on (https://groups.google.com/forum/#!topic/golang-nuts/4ebvN6Bgv3M) somebody comments that:

  • the driver don't know the destination type (only the source/persisted type),
  • the driver should not return a string but a byte[](mattn's driver seems to ignore this rule) (see driver.Rows.Next documentation),
  • there is no converter from byte[]/string to time.Time (see convertAssign).

Mac FTS Issues

I recently updated to the new version of your code and could no longer create FTS tables, I got the following error "no such module: FTS4" even though sqlite3 had been built with fts enabled.

I managed to narrow it down to working on the following commit:
a3e3a8e

After this commit it stops working.

Runtime error in LastInsertId & RowsAffected when using multiple goroutines

I sometimes get errors when using the driver with multiple goroutines, from the LastInsertId & RowsAffected methods - it appears that sometimes the db field of the SQLiteConn structure is nil:

goroutine 9 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_changes(0x0, 0xf8402f2400)
github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:114 +0x2f
github.com/mattn/go-sqlite3.(_SQLiteResult).RowsAffected(0xf840248c40, 0xf84024b390, 0x0, 0x0)
github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:265 +0x2e
database/sql.(_result).RowsAffected(0xf84024b390, 0xf8401b1a00, 0xfc, 0xf8402f2400)
/usr/local/go/src/pkg/database/sql/convert.go:0 +0x43
github.com/coopernurse/gorp.update(0xf840070d80, 0xf8400960c0, 0xf840070d80, 0x2568f90, 0x100000001, ...)
/Users/gutter/dev/poundsmtp/src/github.com/coopernurse/gorp/gorp.go:1095 +0x386
github.com/coopernurse/gorp.(*DbMap).Update(0xf840070d80, 0x2568f90, 0x100000001, 0xf8400ac510, 0x20ede0, ...)
/Users/gutter/dev/poundsmtp/src/github.com/coopernurse/gorp/gorp.go:658 +0x6e
main.validateMessages(0xf840110c60, 0xf8401adb40, 0x0, 0x0)
/Users/gutter/dev/poundsmtp/src/validate.go:325 +0x4ad
created by main.checkAccount
/Users/gutter/dev/poundsmtp/src/validate.go:84 +0x370

Compiling on OSX fails

With the current version of go-sqlite3 I am just getting an error when I try to compile it.
I'm on OSX 10.8.4 and go 1.1.2 (darwin/amd64)

Output when I execute: go get -x github.com/mattn/go-sqlite3

WORK=/var/folders/9l/csqg64n15vq6nytsrkr2jz3w0000gn/T/go-build080659724
mkdir -p $WORK/github.com/mattn/go-sqlite3/_obj/
mkdir -p $WORK/github.com/mattn/
cd /Users/simon/Dropbox/Development/go/src/github.com/mattn/go-sqlite3
pkg-config --cflags sqlite3
pkg-config --libs sqlite3
/usr/local/go/pkg/tool/darwin_amd64/cgo -objdir $WORK/github.com/mattn/go-sqlite3/_obj/ -- -I/usr/local/Cellar/sqlite/3.8.0.2/include -I $WORK/github.com/mattn/go-sqlite3/_obj/ sqlite3.go sqlite3_other.go
# github.com/mattn/go-sqlite3
clang: error: argument unused during compilation: '-fno-eliminate-unused-debug-types' 

go-sql-test fails

Here is a patch to make go-sql-test pass:

  1. an unrelated fix to make your TestBooleanRoundtrip pass,
  2. a fix in Rows.Close to reset the Stmt but not close it,
  3. a fix to set a default busy timeout.
diff --git a/sqlite3.go b/sqlite3.go
index 02e7107..e3ce711 100644
--- a/sqlite3.go
+++ b/sqlite3.go
@@ -91,6 +91,12 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
        if db == nil {
                return nil, errors.New("sqlite succeeded without returning a database")
        }
+
+       rv = C.sqlite3_busy_timeout(db, 500)
+       if rv != C.SQLITE_OK {
+               return nil, errors.New(C.GoString(C.sqlite3_errmsg(db)))
+       }
+
        return &SQLiteConn{db}, nil
 }

@@ -174,7 +180,7 @@ func (s *SQLiteStmt) bind(args []driver.Value) error {
                        rv = C.sqlite3_bind_int(s.s, n, C.int(v))
                case bool:
                        if bool(v) {
-                               rv = C.sqlite3_bind_int(s.s, n, -1)
+                               rv = C.sqlite3_bind_int(s.s, n, 1)
                        } else {
                                rv = C.sqlite3_bind_int(s.s, n, 0)
                        }
@@ -233,7 +239,11 @@ type SQLiteRows struct {
 }

 func (rc *SQLiteRows) Close() error {
-       return rc.s.Close()
+       rv := C.sqlite3_reset(rc.s.s)
+       if rv != C.SQLITE_OK {
+               return errors.New(C.GoString(C.sqlite3_errmsg(rc.s.c.db)))
+       }
+       return nil
 }

 func (rc *SQLiteRows) Columns() []string {

crash when try to commit changes

Hello. i'm use sqlite3 binding in go get bitbucket.org/vase/go-aps
if its run wia aps -u after some time (massive import to db) its crashed,

Loading Go Runtime support.
(gdb) run -u
Starting program: /home/vase/projects/aps/aps -u
warning: Unable to find libthread_db matching inferior's thread library, thread debugging will not be available.

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b4719b in ?? () from /usr/lib64/libsqlite3.so.0
(gdb) bt
#0  0x00007ffff7b4719b in ?? () from /usr/lib64/libsqlite3.so.0
#1  0x00007ffff7b59c5d in ?? () from /usr/lib64/libsqlite3.so.0
#2  0x00007ffff7b60ee8 in ?? () from /usr/lib64/libsqlite3.so.0
#3  0x00007ffff7b60f59 in ?? () from /usr/lib64/libsqlite3.so.0
#4  0x00007ffff7b8fbf1 in sqlite3_finalize () from /usr/lib64/libsqlite3.so.0
#5  0x00007ffff7b8fc6e in ?? () from /usr/lib64/libsqlite3.so.0
#6  0x00007ffff7b496bf in ?? () from /usr/lib64/libsqlite3.so.0
#7  0x00007ffff7b4974c in ?? () from /usr/lib64/libsqlite3.so.0
#8  0x00007ffff7b56575 in ?? () from /usr/lib64/libsqlite3.so.0
#9  0x00007ffff7b88be9 in sqlite3_close () from /usr/lib64/libsqlite3.so.0
#10 0x000000000046205c in _cgo_4a89d1bfa1bc_Cfunc_sqlite3_close ()
#11 0x00007ffff7f8e720 in ?? ()
#12 0x0000000000418de5 in runtime.asmcgocall (fn=void, arg=void) at /tmp/bindist046461602/go/src/pkg/runtime/asm_amd64.s:455
#13 0x000000f840065000 in ?? ()
#14 0x0000000000000020 in ?? ()
#15 0x00007ffff7f8e098 in ?? ()
#16 0x00007ffff7f8e6a0 in ?? ()
#17 0x000000f840065000 in ?? ()
#18 0x0000100000000020 in ?? ()
#19 0x0000000000418c3c in runtime.lessstack () at /tmp/bindist046461602/go/src/pkg/runtime/asm_amd64.s:251
#20 0x000000f840065000 in ?? ()
#21 0x0000000000000000 in ?? ()
(gdb) bt full
#0  0x00007ffff7b4719b in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#1  0x00007ffff7b59c5d in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#2  0x00007ffff7b60ee8 in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#3  0x00007ffff7b60f59 in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#4  0x00007ffff7b8fbf1 in sqlite3_finalize () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#5  0x00007ffff7b8fc6e in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#6  0x00007ffff7b496bf in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#7  0x00007ffff7b4974c in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#8  0x00007ffff7b56575 in ?? () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#9  0x00007ffff7b88be9 in sqlite3_close () from /usr/lib64/libsqlite3.so.0
No symbol table info available.
#10 0x000000000046205c in _cgo_4a89d1bfa1bc_Cfunc_sqlite3_close ()
No locals.
#11 0x00007ffff7f8e720 in ?? ()
No symbol table info available.
#12 0x0000000000418de5 in runtime.asmcgocall (fn=void, arg=void) at /tmp/bindist046461602/go/src/pkg/runtime/asm_amd64.s:455
No locals.
#13 0x000000f840065000 in ?? ()
No symbol table info available.
#14 0x0000000000000020 in ?? ()
No symbol table info available.
#15 0x00007ffff7f8e098 in ?? ()
No symbol table info available.
#16 0x00007ffff7f8e6a0 in ?? ()
No symbol table info available.
#17 0x000000f840065000 in ?? ()
No symbol table info available.
#18 0x0000100000000020 in ?? ()
No symbol table info available.
#19 0x0000000000418c3c in runtime.lessstack () at /tmp/bindist046461602/go/src/pkg/runtime/asm_amd64.s:251
No locals.
#20 0x000000f840065000 in ?? ()
No symbol table info available.
#21 0x0000000000000000 in ?? ()
---Type <return> to continue, or q <return> to quit---No s

LastInsertId returning wrong id

Sample code:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
    "os"
)

func main() {
    os.Remove("./foo.db")

    db, err := sql.Open("sqlite3", "./foo.db")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    sql := "create table foo (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, name text)"

    _, err = db.Exec(sql)
    if err != nil {
        fmt.Printf("%q: %s\n", err, sql)
        return
    }

    result, err := db.Exec("insert into foo(name) values(1)")
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(result.LastInsertId())
    return
}

printing 4294967296 <nil>, should print 1 <nil>.

Can someone else confirm it?

Windows 7 x32, Go 1.0.3, last go-sqlite3.

Best regards

Output of time.Time is to zero value

time.Time is not being correctly handled. Test: http://play.golang.org/p/OBQpuZ87Af

Output:

$ go run db.go
got different data
input:  {1 2009-11-10 23:00:00 +0000 UTC}
output: {1 0001-01-01 00:00:00 +0000 UTC}

got different data
input:  {2 2013-03-09 17:23:27.25302803 +0000 UTC}
output: {2 0001-01-01 00:00:00 +0000 UTC}

Add support for extensions

I tried to add support for loading sqlite3 extensions.
The modification is the following (naive implementation bacause I am new to Go)

diff --git a/sqlite3.go b/sqlite3.go
index b95f290..a4fe4dd 100644
--- a/sqlite3.go
+++ b/sqlite3.go
@@ -71,6 +71,8 @@ var SQLiteTimestampFormats = []string{
    "2006-01-02",
 }

+var LoadExtensionOnOff = 0
+
 func init() {
    sql.Register("sqlite3", &SQLiteDriver{})
 }
@@ -176,6 +178,11 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
        return nil, errors.New(C.GoString(C.sqlite3_errmsg(db)))
    }

+   rv = C.sqlite3_enable_load_extension(db, C.int(LoadExtensionOnOff))
+   if rv != C.SQLITE_OK {
+       return nil, errors.New(C.GoString(C.sqlite3_errmsg(db)))
+   }
+
    return &SQLiteConn{db}, nil
 }

So, when I want to have extensions enabled I just call

sqlite3.EnableExtensionOnOff = 1

before calling sql.Open(...).

This works and I can load my extension using an sql query

_, err = db.Exec("SELECT load_extension('libspatialite')")

BUT, when the line defer db.Close() is used, I get the following error when after trying to close the database

*** Error in `/home/peter/.tmp/go-build467732638/command-line-arguments/_obj/exe/main': double free or corruption (!prev): 0x0000000000babc80 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x72ecf)[0x7fccaf9c0ecf]
/usr/lib/libc.so.6(+0x7869e)[0x7fccaf9c669e]
/usr/lib/libc.so.6(+0x79377)[0x7fccaf9c7377]
/usr/lib/libsqlite3.so.0(sqlite3_free+0x6e)[0x7fccaff2e32e]
/usr/lib/libsqlite3.so.0(+0x2329c)[0x7fccaff3929c]
/usr/lib/libsqlite3.so.0(+0x2331c)[0x7fccaff3931c]
/usr/lib/libsqlite3.so.0(+0x59d36)[0x7fccaff6fd36]
/usr/lib/libsqlite3.so.0(sqlite3_finalize+0x27)[0x7fccaff6fd77]
/usr/lib/libsqlite3.so.0(+0x5a5f4)[0x7fccaff705f4]
/usr/lib/libsqlite3.so.0(+0x5a659)[0x7fccaff70659]
/usr/lib/libsqlite3.so.0(+0x21091)[0x7fccaff37091]
/usr/lib/libsqlite3.so.0(+0x58de1)[0x7fccaff6ede1]
/home/peter/.tmp/go-build467732638/command-line-arguments/_obj/exe/main(_cgo_604110260f67_Cfunc_sqlite3_close+0xc)[0x40210c]
/home/peter/.tmp/go-build467732638/command-line-arguments/_obj/exe/main[0x420b2f]
======= Memory map: ========
00400000-00547000 r-xp 00000000 00:20 11814031                           /home/peter/.tmp/go-build467732638/command-line-arguments/_obj/exe/main
00747000-0075b000 rw-p 00147000 00:20 11814031                           /home/peter/.tmp/go-build467732638/command-line-arguments/_obj/exe/main
0075b000-0076d000 rw-p 00000000 00:00 0 
00ad7000-00bbc000 rw-p 00000000 00:00 0                                  [heap]
c1ffff0000-c200100000 rw-p 00000000 00:00 0 
7fcc90000000-7fcc90021000 rw-p 00000000 00:00 0 
7fcc90021000-7fcc94000000 ---p 00000000 00:00 0 
7fcc98000000-7fcc98021000 rw-p 00000000 00:00 0 
7fcc98021000-7fcc9c000000 ---p 00000000 00:00 0 
7fcc9c2f8000-7fcc9c30d000 r-xp 00000000 08:01 2025308                    /usr/lib/libgcc_s.so.1
7fcc9c30d000-7fcc9c50d000 ---p 00015000 08:01 2025308                    /usr/lib/libgcc_s.so.1
7fcc9c50d000-7fcc9c50e000 rw-p 00015000 08:01 2025308                    /usr/lib/libgcc_s.so.1
7fcc9c50e000-7fcc9c5f4000 r-xp 00000000 08:01 1976278                    /usr/lib/libstdc++.so.6.0.18
7fcc9c5f4000-7fcc9c7f3000 ---p 000e6000 08:01 1976278                    /usr/lib/libstdc++.so.6.0.18
7fcc9c7f3000-7fcc9c7fb000 r--p 000e5000 08:01 1976278                    /usr/lib/libstdc++.so.6.0.18
7fcc9c7fb000-7fcc9c7fd000 rw-p 000ed000 08:01 1976278                    /usr/lib/libstdc++.so.6.0.18
7fcc9c7fd000-7fcc9c812000 rw-p 00000000 00:00 0 
7fcc9c812000-7fcc9c987000 r-xp 00000000 08:01 2021510                    /usr/lib/libgeos-3.3.8.so
7fcc9c987000-7fcc9cb87000 ---p 00175000 08:01 2021510                    /usr/lib/libgeos-3.3.8.so
7fcc9cb87000-7fcc9cb94000 r--p 00175000 08:01 2021510                    /usr/lib/libgeos-3.3.8.so
7fcc9cb94000-7fcc9cb98000 rw-p 00182000 08:01 2021510                    /usr/lib/libgeos-3.3.8.so
7fcc9cb98000-7fcc9cb99000 rw-p 00000000 00:00 0 
7fcc9cb99000-7fcc9cc9b000 r-xp 00000000 08:01 1973269                    /usr/lib/libm-2.18.so
7fcc9cc9b000-7fcc9ce9a000 ---p 00102000 08:01 1973269                    /usr/lib/libm-2.18.so
7fcc9ce9a000-7fcc9ce9b000 r--p 00101000 08:01 1973269                    /usr/lib/libm-2.18.so
7fcc9ce9b000-7fcc9ce9c000 rw-p 00102000 08:01 1973269                    /usr/lib/libm-2.18.so
7fcc9ce9c000-7fcc9cec0000 r-xp 00000000 08:01 2021512                    /usr/lib/libgeos_c.so.1.7.8
7fcc9cec0000-7fcc9d0bf000 ---p 00024000 08:01 2021512                    /usr/lib/libgeos_c.so.1.7.8
7fcc9d0bf000-7fcc9d0c0000 r--p 00023000 08:01 2021512                    /usr/lib/libgeos_c.so.1.7.8
7fcc9d0c0000-7fcc9d0c1000 rw-p 00024000 08:01 2021512                    /usr/lib/libgeos_c.so.1.7.8
7fcc9d0c1000-7fcc9d0d6000 r-xp 00000000 08:01 1976310                    /usr/lib/libz.so.1.2.8
7fcc9d0d6000-7fcc9d2d5000 ---p 00015000 08:01 1976310                    /usr/lib/libz.so.1.2.8
7fcc9d2d5000-7fcc9d2d6000 r--p 00014000 08:01 1976310                    /usr/lib/libz.so.1.2.8
7fcc9d2d6000-7fcc9d2d7000 rw-p 00015000 08:01 1976310                    /usr/lib/libz.so.1.2.8
7fcc9d2d7000-7fcc9d326000 r-xp 00000000 08:01 2021526                    /usr/lib/libproj.so.0.7.0
7fcc9d326000-7fcc9d526000 ---p 0004f000 08:01 2021526                    /usr/lib/libproj.so.0.7.0
7fcc9d526000-7fcc9d527000 r--p 0004f000 08:01 2021526                    /usr/lib/libproj.so.0.7.0
7fcc9d527000-7fcc9d52a000 rw-p 00050000 08:01 2021526                    /usr/lib/libproj.so.0.7.0
7fcc9d52a000-7fcc9d532000 r-xp 00000000 08:01 2021535                    /usr/lib/libfreexl.so.1.0.0
7fcc9d532000-7fcc9d731000 ---p 00008000 08:01 2021535                    /usr/lib/libfreexl.so.1.0.0
7fcc9d731000-7fcc9d732000 r--p 00007000 08:01 2021535                    /usr/lib/libfreexl.so.1.0.0
7fcc9d732000-7fcc9d733000 rw-p 00008000 08:01 2021535                    /usr/lib/libfreexl.so.1.0.0
7fcc9d733000-7fcc9db12000 r-xp 00000000 08:01 2012479                    /usr/lib/libspatialite.so.5.1.0
7fcc9db12000-7fcc9dd11000 ---p 003df000 08:01 2012479                    /usr/lib/libspatialite.so.5.1.0
7fcc9dd11000-7fcc9dd12000 r--p 003de000 08:01 2012479                    /usr/lib/libspatialite.so.5.1.0
7fcc9dd12000-7fcc9dd15000 rw-p 003df000 08:01 2012479                    /usr/lib/libspatialite.so.5.1.0
7fcc9dd4c000-7fcc9dd4d000 ---p 00000000 00:00 0 
7fcc9dd4d000-7fcc9e59d000 rw-p 00000000 00:00 0                          [stack:24291]
7fcc9e59d000-7fcc9e59e000 ---p 00000000 00:00 0 
7fcc9e59e000-7fcc9eeee000 rw-p 00000000 00:00 0 
7fcc9eeee000-7fcc9eeef000 ---p 00000000 00:00 0 
7fcc9eeef000-7fccaf74a000 rw-p 00000000 00:00 0                          [stack:24289]
7fccaf74a000-7fccaf74d000 r-xp 00000000 08:01 1973302                    /usr/lib/libdl-2.18.so
7fccaf74d000-7fccaf94c000 ---p 00003000 08:01 1973302                    /usr/lib/libdl-2.18.so
7fccaf94c000-7fccaf94d000 r--p 00002000 08:01 1973302                    /usr/lib/libdl-2.18.so
7fccaf94d000-7fccaf94e000 rw-p 00003000 08:01 1973302                    /usr/lib/libdl-2.18.so
7fccaf94e000-7fccafaef000 r-xp 00000000 08:01 1973270                    /usr/lib/libc-2.18.so
7fccafaef000-7fccafcee000 ---p 001a1000 08:01 1973270                    /usr/lib/libc-2.18.so
7fccafcee000-7fccafcf2000 r--p 001a0000 08:01 1973270                    /usr/lib/libc-2.18.so
7fccafcf2000-7fccafcf4000 rw-p 001a4000 08:01 1973270                    /usr/lib/libc-2.18.so
7fccafcf4000-7fccafcf8000 rw-p 00000000 00:00 0 
7fccafcf8000-7fccafd10000 r-xp 00000000 08:01 1973229                    /usr/lib/libpthread-2.18.so
7fccafd10000-7fccaff10000 ---p 00018000 08:01 1973229                    /usr/lib/libpthread-2.18.so
7fccaff10000-7fccaff11000 r--p 00018000 08:01 1973229                    /usr/lib/libpthread-2.18.so
7fccaff11000-7fccaff12000 rw-p 00019000 08:01 1973229                    /usr/lib/libpthread-2.18.so
7fccaff12000-7fccaff16000 rw-p 00000000 00:00 0 
7fccaff16000-7fccaffc5000 r-xp 00000000 08:01 1995992                    /usr/lib/libsqlite3.so.0.8.6
7fccaffc5000-7fccb01c5000 ---p 000af000 08:01 1995992                    /usr/lib/libsqlite3.so.0.8.6
7fccb01c5000-7fccb01c7000 r--p 000af000 08:01 1995992                    /usr/lib/libsqlite3.so.0.8.6
7fccb01c7000-7fccb01ca000 rw-p 000b1000 08:01 1995992                    /usr/lib/libsqlite3.so.0.8.6
7fccb01ca000-7fccb01ea000 r-xp 00000000 08:01 1973253                    /usr/lib/ld-2.18.so
7fccb01fd000-7fccb03b2000 rw-p 00000000 00:00 0                          [stack:24290]
7fccb03b7000-7fccb03e9000 rw-p 00000000 00:00 0 
7fccb03e9000-7fccb03ea000 r--p 0001f000 08:01 1973253                    /usr/lib/ld-2.18.so
7fccb03ea000-7fccb03eb000 rw-p 00020000 08:01 1973253                    /usr/lib/ld-2.18.so
7fccb03eb000-7fccb03ec000 rw-p 00000000 00:00 0 
7fff98a31000-7fff98a52000 rw-p 00000000 00:00 0                          [stack]
7fff98b51000-7fff98b53000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
SIGABRT: abort
PC=0x7fccaf9833d9
signal arrived during cgo execution

github.com/ptrv/go-sqlite3._Cfunc_sqlite3_close(0xad71c8, 0x0)
    github.com/ptrv/go-sqlite3/_obj/_cgo_defun.c:152 +0x2f
github.com/ptrv/go-sqlite3.(*SQLiteConn).Close(0xc200000020, 0x0, 0x7fccb035ddb8)
    github.com/ptrv/go-sqlite3/_obj/sqlite3.cgo1.go:171 +0x7f
database/sql.(*driverConn).finalClose(0xc20006d060, 0xc200058300, 0xc20003b230)
    /usr/local/go/src/pkg/database/sql/sql.go:289 +0xcb
database/sql.func·002(0xc20006d000, 0xc2000691b0)
    /usr/local/go/src/pkg/database/sql/sql.go:372 +0x2c
database/sql.(*driverConn).closeDBLocked(0xc20006d060, 0x412974, 0x4f3f70)
    /usr/local/go/src/pkg/database/sql/sql.go:261 +0x133
database/sql.(*DB).Close(0xc20006d000, 0x0, 0x0)
    /usr/local/go/src/pkg/database/sql/sql.go:421 +0xb3
main.main()
    /home/peter/gocode/src/github.com/ptrv/go-spatialite/spatialite_example/main.go:39 +0xf1

goroutine 2 [syscall]:
rax     0x0
rbx     0x92
rcx     0xffffffffffffffff
rdx     0x6
rdi     0x5ee0
rsi     0x5ee0
rbp     0x7fff98a4ff70
rsp     0x7fff98a4fbd8
r8      0x0
r9      0x401fe4
r10     0x8
r11     0x202
r12     0x7fff98a4fd80
r13     0x7
r14     0x92
r15     0x7
rip     0x7fccaf9833d9
rflags  0x202
cs      0x33
fs      0x0
gs      0x0
exit status 2

Any clue what the error message means and how this could be fixed?

If I do not close the database I do not get the error message.

Thanks in advance,
Peter

Is it possible db.Prepare() and use the prepared stmt in tx?

I'm porting my old Go r.60 db code into Go1.
And start to use go-sqlite3 (old go sqlite library on code.google can not work).
My old code can do (pseudo code)

stmt = db.Prepare('insert into TABLE values(?,?)
db.Begin()
for i=0; i<10000; i++ {
  stmt.Exec(i, data[i])
}
db.End()

But, I don't know how to do such thing on go-sqlite3, could you write a test code or example code?
I just know the prepare() must after transaction initialize, that will reduce my code performance.

small doc suggestion

Hello!

I just spent a bit more time than I was hoping to searching for the solution to get sqlite associated with pkgconfig on OS X via homebrew. I ran

brew install pkgconfig
brew install sqlite3

as suggested, but was seeing the following error when trying to validate the installation:

$ pkg-config --cflags --libs sqlite
Package sqlite was not found in the pkg-config search path.
Perhaps you should add the directory containing `sqlite.pc'
to the PKG_CONFIG_PATH environment variable
No package 'sqlite' found

The following reminder in the OS X portion of the ReadMe could be helpful:

You may need to link sqlite3.pc to /usr/local/pkgconfig/ with $ brew link --force sqlite

TIMESTAMP is not in the SQLite3 specification

The type "TIMESTAMP" has been added to this driver but it does not follows the SQLite3 specification (http://sqlite.org/datatype3.html):

1.2 Date and Time Datatype

SQLite does not have a storage class set aside for storing dates and/or >times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

This is an important issue because the SQL code used in Go with this driver would not be valid in others drivers that have followed the specification.

The app runs out of file descriptors when using prepared statements

I've adapted the main.go file of the example to show my error:
https://gist.github.com/ernestokarim/5033404

In the iteration 1021 the app returns an unable to open database file error. Running this in another terminal tab (that's the reason of the initial sleep, to find the correct PID):

 while [ 1 ] ; do ls /proc/6559/fd | wc -l ; sleep 1; done

reveals the number of open file descriptors is increasing all the time, even if I'm closing correctly the prepared statements.

Using a solution taken from other unrelated issue (#39 (comment)) I was able to keep the number of open files around 4 / 5 (in a comment, in the gist)

Is this a known behaviour of the library? Or are we leaking descriptors? There is a better solution to it?

panic: segmentation violation during concurrent SELECTs

When GOMAXPROCS=1 eveything works out fine but with GOMAXPROCS=4 I'm getting

SIGSEGV: segmentation violation
PC=0x7fe715011f7d
signal arrived during cgo execution

github.com/mattn/go-sqlite3._Cfunc__sqlite3_open_v2(0x259def0, 0xc20055e378, 0x10006, 0x0, 0xc1fffc3fa8, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:80 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteDriver).Open(0xc70a80, 0xc200192320, 0x9, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:128 +0x1a2
database/sql.(*DB).conn(0xc2001aef50, 0xc20055e370, 0xffffffffffffffff, 0xc2004269f0)

...
goroutine 74 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_step(0x7fe6a8000e48, 0xff00ffff)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:296 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteRows).Next(0xc200480540, 0xc20055f1a0, 0xd, 0xd, 0xd, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:323 +0x3a

...
goroutine 72 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_prepare_v2(0x7fe6bc0008e8, 0x7fe6bc011ca0, 0x7fe6ffffffff, 0xc200677008, 0xc200677010, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:278 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteConn).Prepare(0xc200677000, 0x86da50, 0xaf, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:174 +0xf5

...
goroutine 75 [syscall]:
github.com/mattn/go-sqlite3._Cfunc__sqlite3_open_v2(0x7fe6d4013ad0, 0xc20055e090, 0x7fe600010006, 0x0, 0x4, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:80 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteDriver).Open(0xc70a80, 0xc200192320, 0x9, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:128 +0x1a2

...
goroutine 71 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_prepare_v2(0x7fe6ec0158c8, 0x7fe6ec0021f0, 0x7fe6ffffffff, 0xc20044bb28, 0xc20044bb30, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:278 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteConn).Prepare(0xc20044bb20, 0x85df90, 0x41, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:174 +0xf5

...
goroutine 81 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_prepare_v2(0x7fe6d40008c8, 0x7fe6f00008c0, 0x7fe6ffffffff, 0xc20055e070, 0xc20055e078, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:278 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteConn).Prepare(0xc2006778a0, 0x86da50, 0xaf, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:174 +0xf5

...
goroutine 77 [syscall]:
github.com/mattn/go-sqlite3._Cfunc__sqlite3_open_v2(0x7fe6b00008c0, 0xc20055e558, 0x7fe600010006, 0x0, 0x4, ...)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:80 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteDriver).Open(0xc70a80, 0xc200192320, 0x9, 0x0, 0x0, ...)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:128 +0x1a2

...
goroutine 78 [syscall]:
github.com/mattn/go-sqlite3._Cfunc_sqlite3_close(0x7fe6d80008c8, 0x0)
        github.com/mattn/go-sqlite3/_obj/_cgo_defun.c:152 +0x2f
github.com/mattn/go-sqlite3.(*SQLiteConn).Close(0xc200677260, 0x7483e0, 0x4e68dd)
        github.com/mattn/go-sqlite3/_obj/sqlite3.cgo1.go:159 +0x7f

...
and so on

I'm basically running basic & simple SELECT queries, and scanning & closing rows.
Am I getting bitten by this? If yes, I'm wondering how should correct go programs be written: use locks for almost everything? use LockOSThread?

Windows installation instructions?

Hello,
I looked at the README and issues, but I have not been successful at using this on Windows 7 64-bit.

When I run go get github.com/mattn/go-sqlite3 it just says:

C:\gocode\src\github.com\robfig\revel [master +2 ~0 -0 !]> go get github.com/mattn/go-sqlite3
# github.com/mattn/go-sqlite3
exec gcc: exec: "gcc": executable file not found in %PATH%

I installed Go 1.0.3 pre-compiled, but I don't have Visual Studio, MinGW or any other Linux emulation. Do I need that?

I'm sure this is a dumb question, but I am new to developing on Windows, and I'm not sure how best to proceed.

Thanks for your help,
Rob

Works with 64-bit Windows (without pkg-config) but doesn't work with 32-bit Windows.

Hello. I've been having trouble with getting this to work on Windows using 32-bit and then found that it works on 64-bit Windows even without pkg-config (which incidentally I had got installed though I'm not sure that could help after all). Having learned more about the current head revision I understand that it works without pkg-config on Windows however I could not get it to work with 32-bit Windows and I get a stream of error messages like "__divdi3: not defined". My understanding of C and cgo is patchy and I'm not sure what this means. I couldn't see why it should be different on 32-bit Windows but perhaps some other compiler option is required.

I resolved my problems by discarding pkg-config and the static compilation on Windows and use the DLL instead, which is what other platforms are using anyway. So instead of the #cgo pkg-config line I'm using "#cgo LDFLAGS: -lsqlite3" having the environment set up with the include files on the path for gcc (LIBRARY_PATH and C_INCLUDE_PATH). The little work with cgo that I've done so far this works best with the smallest of changes to the source-code across platforms.

I've never used pkg-config before and while I had no trouble with it on other platforms on Windows it was a struggle getting an environment set up. Wouldn't this be better without pkg-config?

In any case the current head revision doesn't appear to work for 32-bit Windows and the static compilation as an exception for Windows seems unnecessarily complicated. Maybe you can get it to work but I wonder if this is the wrong direction to go.

Support for *sql.RawBytes

According to the database/sql docs

If an argument has type *interface{}, Scan copies the value provided by the underlying driver without conversion. If the value is of type []byte, a copy is made and the caller owns the result.

So, if we were following the docs and use *interface{} or []byte we should be able to get a raw piece of bytes ad result from the Scan(), but I don't see how this could be achieved with the corrent driver:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
    "os"
)

func main() {
    os.Remove("./foo.db")

    db, err := sql.Open("sqlite3", "./foo.db")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    sqls := []string{
        "create table foo (id integer not null primary key, name text)",
        "delete from foo",
    }
    for _, sql := range sqls {
        _, err = db.Exec(sql)
        if err != nil {
            fmt.Printf("%q: %s\n", err, sql)
            return
        }
    }

    for i := 0; i < 2; i++ {
        db.Exec(`INSERT INTO foo (name) VALUES ("Hello")`)
    }

    rows, err := db.Query(`SELECT * from foo`)

    for rows.Next() {
        columns, _ := rows.Columns()
        values := make([][]byte, len(columns))

        scanArgs := make([]interface{}, len(values))

        for i := range values {
            scanArgs[i] = &values[i]
        }

        rows.Scan(scanArgs...)

        var value string
        for i, col := range values {

            if col == nil {
                value = "NULL"
            } else {
                value = string(col)
            }

            fmt.Printf("%s: %v\n", columns[i], value)
        }
    }

}

I took the above example from another SQL driver that does not handle conversions by itself and instead lets conversions happen in database/sql.

We could use *sql.RawBytes instead of []byte and the result is the same.

Now, I've tried to make a workaround but I don't see how can make it compatible with all conversions go-sqlite3 does, the main problem seems to be handling conversions on go-sqlite3 and that's one of the features of the package.

Do you have any thoughs on how this could be implemented? I would be happy to send a fix if we could figure out what to do.

SELECT Query not working

I have SQLite3 3.15.x on Windows 7 64 bit but the GCC and go (version 1.1) are 32 bit.
The SELECT queries are not working for some reason.
At times its leads to PANIC when the query is executed. Is there an issue with 32 bit version on Windows ?
The following is the error returned with err.Error() :
U??S??►??3?

Issue installing on Mac OS

Had some problems installing the lib on Mac, so just wanted to leave this here for future people searching for help:

after

brew install pkgconfig
brew install sqlite3

I've tried pkg-config --cflags --libs sqlite3, but got:

# pkg-config --cflags sqlite3
Package sqlite3 was not found in the pkg-config search path.
Perhaps you should add the directory containing `sqlite3.pc'
to the PKG_CONFIG_PATH environment variable
No package 'sqlite3' found
exit status 1

What you need to do:

sudo PKG_CONFIG_PATH=/usr/local/Cellar/sqlite/3.7.15.2/lib/pkgconfig/ go get github.com/mattn/go-sqlite3

Please replace 3.7.15.2 with your version.

Thanks for the lib!

panic: "database table is locked" when multiple writes occur concurrently

I encountered the problem from Issue 39 and applied the resolution of adding "?cache=shared&mode=rwc" to my open string. Now, when multiple writers run concurrently, I encounter a different error:

panic: database table is locked: <table name>

Some research indicate SQLite has an API for waiting for the locking query to finish so the next query can be run. Please implement this, so that manually managing concurrent writes, or write retries, is unnecessary.

https://www.sqlite.org/unlock_notify.html

can't build: 'sqlite3_errstr' undeclared

go get github.com/mattn/go-sqlite3 fails to build with the following error:

1: error: 'sqlite3_errstr' undeclared (first use in this function)
1: note: each undeclared identifier is reported only once for each function it appears in

please advise.

Trouble installing on windows

I'm installing into Windows 8 64 bit

When I run: go get github.com/mattn/go-sqlite3
I get this:

github.com/mattn/go-sqlite3

In file included from sqlite3.go:4:
sqlite3.h:35: stdarg.h: No such file or directory
sqlite3.go:5: stdlib.h: No such file or directory
sqlite3.go:6: string.h: No such file or directory
sqlite3.go:35: stdio.h: No such file or directory
sqlite3.go:36: stdint.h: No such file or directory

Any ideas of what's screwing up?

I saw that there's an issue for a Windows 64 bit bug here:
#27

But I don't think it's the same issue..?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.