Files
khatru/storage/postgresql/init.go
alex 627724f702 start: introduce Server type and Shutdown (breaking change)
the main motivation for this change is to be able to run tests.
before this commit, Start, Router and Log operated on global variables,
making automated testing unreasonably hard.

this commit puts all that a server needs in a new Server type,
which also made it possible for a Server.Shutdown - see ShutdownAware
doc comments.

BREAKING CHANGES:
- Relay.OnInitialized takes one argument now, *relayer.Server.
- relayer.Router is now replaced by relayer.Server.Router().
  package users can still hook into the router from OnInitialized
  for custom HTTP routing.
- relayer.Log is gone. apart from another global var, imho this was
  a too opinionated choice for a framework to build a custom relay upon.
  this commit introduces a Logger interface which package users can implement
  for zerolog to make it log like before. see Server.Log for details.

other notable changes: finally added a couple basic tests, for start up
and shutdown. doc comments now explain most of the essentials,
hopefully making it more approachable for newcomers and easier to understand
the relayer package.

the changes in handlers.go are minimal, although git diff goes crazy.
this is because most of the lines are simply shifted indentation back by one
due to go fmt.

before this commit:

    func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request)
    func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request)

after:

    func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request)
    func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 20:41:02 -03:00

45 lines
1.2 KiB
Go

package postgresql
import (
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
_ "github.com/lib/pq"
)
func (b *PostgresBackend) Init() error {
db, err := sqlx.Connect("postgres", b.DatabaseURL)
if err != nil {
return err
}
db.Mapper = reflectx.NewMapperFunc("json", sqlx.NameMapper)
b.DB = db
_, err = b.DB.Exec(`
CREATE OR REPLACE FUNCTION tags_to_tagvalues(jsonb) RETURNS text[]
AS 'SELECT array_agg(t->>1) FROM (SELECT jsonb_array_elements($1) AS t)s WHERE length(t->>0) = 1;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
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,
tagvalues text[] GENERATED ALWAYS AS (tags_to_tagvalues(tags)) STORED
);
CREATE UNIQUE INDEX IF NOT EXISTS ididx ON event USING btree (id text_pattern_ops);
CREATE INDEX IF NOT EXISTS pubkeyprefix ON event USING btree (pubkey text_pattern_ops);
CREATE INDEX IF NOT EXISTS timeidx ON event (created_at);
CREATE INDEX IF NOT EXISTS kindidx ON event (kind);
CREATE INDEX IF NOT EXISTS arbitrarytagvalues ON event USING gin (tagvalues);
`)
return err
}