Skip to content

Commit

Permalink
Merge pull request #91 from mattn/ext-sqlite3
Browse files Browse the repository at this point in the history
create index for storage/sqlite3
  • Loading branch information
mattn committed Oct 5, 2023
2 parents 4e412d3 + 4782a43 commit 991bcc1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 15 deletions.
60 changes: 46 additions & 14 deletions storage/sqlite3/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,60 @@ import (

var _ relayer.Storage = (*SQLite3Backend)(nil)

var ddls = []string{
`CREATE TABLE IF NOT EXISTS event (
id text NOT NULL,
pubkey text NOT NULL,
created_at integer NOT NULL,
kind integer NOT NULL,
tags jsonb NOT NULL,
content text NOT NULL,
sig text NOT NULL);`,
`CREATE UNIQUE INDEX IF NOT EXISTS ididx ON event(id)`,
`CREATE INDEX IF NOT EXISTS pubkeyprefix ON event(pubkey)`,
`CREATE INDEX IF NOT EXISTS timeidx ON event(created_at DESC)`,
`CREATE INDEX IF NOT EXISTS kindidx ON event(kind)`,
}

func fixup(db *sqlx.DB) {
row, err := db.Query(`SELECT id, rowid FROM event GROUP BY id HAVING COUNT(id) > 1`)
if err == nil {
for row.Next() {
var id, rowid string
err = row.Scan(&id, &rowid)
if err != nil {
continue
}
result, err := db.Exec(`DELETE FROM event WHERE id = ? AND rowid != ?`, id, rowid)
if err != nil {
continue
}
num, _ := result.RowsAffected()
println(id, rowid, num)
}
row.Close()
println("DONE")
}
}

func (b *SQLite3Backend) Init() error {
db, err := sqlx.Connect("sqlite3", b.DatabaseURL)
if err != nil {
return err
}
fixup(db)

// sqlx default is 0 (unlimited), while sqlite3 by default accepts up to 100 connections
db.SetMaxOpenConns(80)
db.SetMaxOpenConns(b.MaxOpenConns)
db.SetMaxIdleConns(b.MaxIdleConns)

db.Mapper = reflectx.NewMapperFunc("json", sqlx.NameMapper)
b.DB = db

_, err = b.DB.Exec(`
CREATE TABLE IF NOT EXISTS event (
id text NOT NULL,
pubkey text NOT NULL,
created_at integer NOT NULL,
kind integer NOT NULL,
tags jsonb NOT NULL,
content text NOT NULL,
sig text NOT NULL
);
`)
return err
for _, ddl := range ddls {
_, err = b.DB.Exec(ddl)
if err != nil {
return err
}
}
return nil
}
4 changes: 3 additions & 1 deletion storage/sqlite3/sqlite3.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ import (

type SQLite3Backend struct {
*sqlx.DB
DatabaseURL string
DatabaseURL string
MaxOpenConns int
MaxIdleConns int
}

0 comments on commit 991bcc1

Please sign in to comment.