Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create index for storage/sqlite3 #91

Merged
merged 4 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
Loading