From 96acbb755adbfd77970369d27f6f355147dfc70f Mon Sep 17 00:00:00 2001 From: Mark Haines Date: Sun, 5 Feb 2017 15:54:51 +0000 Subject: [PATCH] Add room ID storage --- .../dendrite/roomserver/storage/sql.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/sql.go b/src/github.com/matrix-org/dendrite/roomserver/storage/sql.go index c1ecfa0b9..0e0529e65 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/sql.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/sql.go @@ -12,6 +12,8 @@ type statements struct { selectEventTypeNIDStmt *sql.Stmt insertEventStateKeyNIDStmt *sql.Stmt selectEventStateKeyNIDStmt *sql.Stmt + insertRoomNIDStmt *sql.Stmt + selectRoomNIDStmt *sql.Stmt } func (s *statements) prepare(db *sql.DB) error { @@ -29,6 +31,10 @@ func (s *statements) prepare(db *sql.DB) error { return err } + if err = s.prepareRooms(db); err != nil { + return err + } + return nil } @@ -226,3 +232,54 @@ func (s *statements) selectEventStateKeyNID(eventStateKey string) (eventStateKey } return } + +func (s *statements) prepareRooms(db *sql.DB) (err error) { + _, err = db.Exec(roomsSchema) + if err != nil { + return + } + if s.insertRoomNIDStmt, err = db.Prepare(insertRoomNIDSQL); err != nil { + return + } + if s.selectRoomNIDStmt, err = db.Prepare(selectRoomNIDSQL); err != nil { + return + } + return +} + +const roomsSchema = ` +CREATE SEQUENCE IF NOT EXISTS room_nid_seq; +CREATE TABLE rooms ( + -- Local numeric ID for the room. + room_nid BIGINT PRIMARY KEY DEFAULT nextvalue('room_nid_seq'), + -- Textual ID for the room. + room_id TEXT NOT NULL CONSTRAINT room_id_unique UNIQUE +); +` + +const insertRoomNIDSQL = "" + + "INSERT INTO rooms (room_id) VALUES ($1)" + + " ON CONFLICT ON CONSTRAINT room_id_unique" + + " DO UPDATE SET room_id = $1" + + " RETURNING (room_nid)" + +const selectRoomNIDSQL = "" + + "SELECT room_nid FROM rooms WHERE room_id = $1" + +func (s *statements) insertRoomNID(roomID string) (roomNID int64, err error) { + err = s.insertRoomNIDStmt.QueryRow(roomID).Scan(&roomNID) + if err == sql.ErrNoRows { + roomNID = 0 + err = nil + } + return +} + +func (s *statements) selectRoomNID(roomID string) (roomNID int64, err error) { + err = s.selectRoomNIDStmt.QueryRow(roomID).Scan(&roomNID) + if err == sql.ErrNoRows { + roomNID = 0 + err = nil + } + return +}