focalboard/server/services/store/sqlstore/board.go
Chen-I Lim c3a4921ac3
GetBoardMetadata API (#2569)
* wip

* Added data migration for populating categories

* wip

* Added data migration for populating categories

* Store WIP

* migration WIP

* category CRUD APIs complete

* category block API WIP

* block category update API done

* Fetcehed data into store

* Started displayting sidebar data

* sidebar WIP

* Dashboard - basic changes

* Sidebar dashboard btn and board switcher UI only

* Sidebar dashboard btn and board switcher UI only

* create category dialog WIP

* Create category webapp side done

* Integrated move card to other category

* board to block

* Disabled dashboard route for now as we'll implement it in phase 2

* WIP

* Added logic to open last board/view on per team level

* Add workspace to teams and boards migrations (#1986)

* Add workspace to teams and boards migrations

* Update json annotations on board models

* boards search dialog WIP

* Seach dialog WIP

* Implemented opening boiard from search results

* Boards switcher styliung

* Handled update category WS event

* Template support

* personal server support and styling fixes

* test fix WIP

* Fixed a bug causing boards to not be moved correctly beteen categories

* Fixed webapp tests

* fix

* Store changes (#2011)

* Permissions phase 1 - Websocket updates (#2014)

* Store changes

* Websockets changes

* Permissions phase 1 - Permissions service (#2015)

* Store changes

* Websockets changes

* Permissions service

* Api and app updates (#2016)

* Store changes

* Websockets changes

* Permissions service

* New API and App changes

* Delete and Patch boards and blocks endpoints

* Used correct variable

* Webapp changes WIP

* Open correct team URL

* Fixed get block API

* Used React context for workspace users

* WIP

* On load navigation sorted out

* WIP

* Nav fix

* categories WS broadcast

* Used real search API

* Fixed unfurl ppreview

* set active team in sidebar

* IMplemented navigation on changing team in sidebar

* Misc fixes

* close rows inside transaction (#2045)

* update syntax for mysql (#2044)

* Upadted mutator for new patchBlock API

* Updated patchBlock API to use new URL

* Listeining to correct event in plugin mode

* Implemented WS messages for category operations:

* Fix duplicated build tags on Makefile

* Sidebar enhancements

* Add missing prefix to SQLite migration and fix flaky tests

* Sidebar boards menu enhancement

* Fix board page interactions (#2144)

* Fix patch board card properties error

* Fix board interactions

* Fix insert blocks interactions

* Fix app tests (#2104)

* Add json1 tag to vscode launch (#2157)

* Fix add, delete and update boards and add board patch generation (#2146)

* Fix update boards and add board patch generation

* Make add board and add template work, as well as deleting a board

* Update the state on board deletion

* Delete unused variable

* Fix bad parenthesis

* Fix board creation inside plugin, options were coming null due websocket message serialization

* update property type mutators to use boards API (#2168)

* Add permissions modal (#2196)

* Initial integration

* Permissions modal, websocket updates and API tests implemented

* Avoid updating/removing user if there is only one admin left

* Fix duplicates on board search

* Adds integration test

* Addressing PR review comments

Co-authored-by: Jesús Espino <jespinog@gmail.com>

* Merge

* I'm able to compile now

* Some fixes around tests execution

* Fixing migrations

* Fixing migrations order

* WIP

* Fixing some other compilation problems on tests

* Some typescript tests fixed

* Fixing javascript tests

* Fixing compilation

* Fixing some problems to create boards

* Load the templates on initial load

* Improvements over initial team templates import

* Adding new fields in the database

* Working on adding duplicate board api

* Removing RootID concept entirely

* Improving a bit the subscriptions

* Fixing store tests for notificationHints

* Fixing more tests

* fixing tests

* Fixing tests

* Fixing tests

* Fixing some small bugs related to templates

* Fixing registration link generation/regeneration

* Fixing cypress tests

* Adding store tests for duplicateBoard and duplicateBlock

* Addressing some TODO comments

* Making the export api simpler

* Add redirect component for old workspace urls

* Removing Dashboard code

* Delete only the built-in templates on update

* fixing tests

* Adding users autocompletion

* Updating snapshots

* Fixing bad merge

* fix panic when creating new card in notifysubscriptions (#2352)

* fix lint errors (#2353)

* fix lint errors

* fix panic when creating new card in notifysubscriptions (#2352)

* fix lint errors

* fix unit test

* Revert "fix unit test"

This reverts commit 0ad78aed65.

Co-authored-by: Doug Lauder <wiggin77@warpmail.net>

* fix sql syntax error for SearchUsersByTeam (#2357)

* Fix mentions delivery (#2358)

* fix sql syntax error for SearchUsersByTeam

* fix mentions delivery

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* update api for octoClient calls, pass correct variables to mutator (#2359)

* Fixing tests after merge

* Fix sidebar context menu UI issue (#2399)

* Fix notification diff for text blocks (#2386)

* fix notification diff for text blocks; fix various linter errors.

* fix URLs to cards

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* Permissions branch: Fix card links (#2391)

* fix notification diff for text blocks; fix various linter errors.

* fix URLs to cards

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* Fixing sqlite tests

* Fixing server tests

* Update migrations to create global templates. (#2397)

* fix duplicate templates

* revert migrate.go

* update UI for empty templates

* implement updating built-in templates as global (teamId = 0)

* handle error if board not found

* update unit test

* fix more tests

* Update blocks_test.go

Fix merge issue

* fix migration sql error (#2414)

* Fixing frontend tests

* Set target team ID when using a global template (#2419)

* Fix some server tests

* Fixing onboarding creation

* Permissions branch: Fix unit tests and CI errors (part 1) (#2425)

* Fixing some small memory leaks (#2400)

* Fixing some small memory leaks

* fixing tests

* passing the tags to all test targets

* Increasing the timeout of the tests

* Fix some type checkings

* Permissions branch: Fixes all the linter errors (#2429)

* fix linter errors

* Reestructuring the router and splitting in more subcomponents (#2403)

* Reestructuring the router and splitting in more subcomponents

* Removing console.log calls

* Removing unneeded selector

* Addressing PR comment

* Fix redirection to one team when you load directly the boards home path

* Using properly the lastTeamID to redirect the user if needed

* don't allow last admin change/deleted (#2416)

* don't allow last admin change/deleted

* update for i18-extract

* fixed en.json

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Harshil Sharma <harshilsharma63@gmail.com>

* Splitting BoardPage component into simpler/smaller components (#2435)

* Splitting BoardPage component into simpler/smaller components

* Removing unneeded import

* Replace go migrate with morph permissions (#2424)

* merge origin/replace-go-migrate-with-morph

* run go mod tidy on mattermost-plugin and increase test timeout

* fix merge issue temprorarily

* remove some debug changes

* fixing the linter

* Allow always team 0 (global) templates fetch (#2472)

* Fix problem with viewId 0 in the URL (#2473)

* Migrate from binddata to goembed (#2471)

* Adding join logic to the board switcher (#2434)

* Adding join logic to the board switcher

* Using already existing client function and removing the joinBoard one

* Adding support for autojoin based on url

* Fixing frontend tests

* fix webapp compile error, missing enableSharedBoards (#2501)

* Fixing duplication on postgres

* Adding back views to the sidebar (#2494)

* Fix #2507. Update Swagger comments (#2508)

* Fix the flash of the template selector on board/team switch (#2490)

* Fix the flash of the template selector on board/team switch

* More fixes specially around error handling

* Fixing the bot badge (#2487)

* simplifying a bit the team store sync between channels and focalboard (#2481)

* Fix menu tests (#2528)

* fix failing menu tests

* fix lint error

* Added keyboard shortcut for boards switcher (#2407)

* Added keyboard shortcut for boards switcher

* Fixed a type error

* Added some inline comments

* Fixed lint

* Fixed bug with scroll jumping when the card is opened: (#2477)

- avoid remounting of `ScrollingComponent` for each render of `Kanban` component
  - property `autoFocus` set to false for `CalculationOptions` because it triggers `blur` even for the button in Jest tests and closes the menu
  - snapshots for tests with `CalculationOptions` updated

* Adding the frontend support for permissions and applying it to a big part of the interface. (#2536)

* Initial work on permissions gates

* Applying permissions gates in more places

* Adding more checks to the interface

* Adding more permissions gates and keeping the store up to date

* fixing some tests

* Fixing some more tests

* Fixing another test

* Fixing all tests and adding some more

* Adding no-permission snapshot tests

* Addressing PR review comments

* Fixing invert behavior

* Permissions branch:  No sqlstore calls after app shutdown (#2530)

* fix webapp compile error, missing enableSharedBoards

* refactor app init wip

* - ensure all block change notifications are finished before shutting down app
- fix unit tests for mysql (insert_at only has 1 second resolution!)

* adjust logging

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* Fixed migrations to allow upgrading from previous version (#2535)

* Added mechanism to check if schema migration is needed

* WIP

* WIP

* WIP

* WIP

* Fixed migration

* Fixed for SQLite

* minor cleaniup

* Deleted old schema migration table after running migrations

* Removed a debug log

* Fixed a bug where the code always tried to delete a table which may or may not exist

* Show properly the user avatar in the ShareBoard component (#2542)

* Fixing the last CI problems from the permissions-branch (#2541)

* Fix history ordering

* Giving some times to avoid possible race conditions

* Empty

* Reverting accidental change in the config.json

* Optimizing table view (#2540)

* Optimizing table view

* Reducing the amount of rendering for tables

* Some other performance improvements

* Improve the activeView updates

* Some extra simplifications

* Another small improvement

* Fixing tests

* Fixing linter errors

* Reducing a bit the amount of dependency with big objects in the store

* Small simplification

* Removing Commenter role from the user role selector (#2561)

* Shareboard cleanup (#2550)

* Initial work on permissions gates

* Applying permissions gates in more places

* Adding more checks to the interface

* Adding more permissions gates and keeping the store up to date

* fixing some tests

* Fixing some more tests

* Fixing another test

* Fixing all tests and adding some more

* Adding no-permission snapshot tests

* Addressing PR review comments

* cleanup some shareboard settings

* remove unused property, fix for user items being displayed for non admin

* revert change, allow users to show

Co-authored-by: Jesús Espino <jespinog@gmail.com>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* GetBoardMetadata API

* Integration tests. WIP

* getBoardHistory

* Working integration test

* Fix ordering, add store tests

* Fix: Update board_history update_at on patch

* sqltests

* Fix unmarshall delete boards_history

* testGetBlockMetadata with delete and undelete

* Handle board not found

* Fixing comments and cards with the new optimizations in the store (#2560)

* Fixing property creation (#2563)

* Cleanup

* Fix user selection in table view (#2565)

* Fixing focus new row in table view (#2567)

* Permissions branch: Fix sqlite table lock (CI) (#2568)

* fix sqlite table lock

* remove test db on teardown

* revert .gitignore

* fix goimport on migration code

* fix typo

* more linter fixes

* clean up tmp db for sqlstore tests

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* Fixing snapshots

* Remove debug log

* Return metadata for deleted boards

* Migrating center panel to functional component (#2562)

* Migrating center panel to functional component

* Fixing some tests

* Fixing another test

* Fixing linter errors

* Fixing types errors

* Fixing linter error

* Fixing cypress tests

* Fixing the last cypress test

* Simpliying a bit the code

* Making property insertion more robust

* Updating checkbox test

* License check

* Cleanup and update Swagger docs

* Merge from main

* Fix bad merge

* Fix Linux-app build break

* do mod tidy

* Fix server lint

* Require credentials (not only read token)

* Add missing defer CloseRows

* do mod tidy

Co-authored-by: Harshil Sharma <harshilsharma63@gmail.com>
Co-authored-by: Miguel de la Cruz <miguel@mcrx.me>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Jesús Espino <jespinog@gmail.com>
Co-authored-by: Doug Lauder <wiggin77@warpmail.net>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Harshil Sharma <18575143+harshilsharma63@users.noreply.github.com>
Co-authored-by: Ibrahim Serdar Acikgoz <serdaracikgoz86@gmail.com>
Co-authored-by: kamre <eremchenko@gmail.com>
2022-03-29 14:47:49 -07:00

712 lines
18 KiB
Go

package sqlstore
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/mattermost/focalboard/server/utils"
sq "github.com/Masterminds/squirrel"
"github.com/mattermost/focalboard/server/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
type BoardNotFoundErr struct {
boardID string
}
func (be BoardNotFoundErr) Error() string {
return fmt.Sprintf("board not found (board id: %s", be.boardID)
}
func boardFields(prefix string) []string {
fields := []string{
"id",
"team_id",
"channel_id",
"created_by",
"modified_by",
"type",
"title",
"description",
"icon",
"show_description",
"is_template",
"template_version",
"COALESCE(properties, '{}')",
"COALESCE(card_properties, '[]')",
"COALESCE(column_calculations, '{}')",
"create_at",
"update_at",
"delete_at",
}
if prefix == "" {
return fields
}
prefixedFields := make([]string, len(fields))
for i, field := range fields {
if strings.HasPrefix(field, "COALESCE(") {
prefixedFields[i] = strings.Replace(field, "COALESCE(", "COALESCE("+prefix, 1)
} else {
prefixedFields[i] = prefix + field
}
}
return prefixedFields
}
func boardHistoryFields() []string {
fields := []string{
"id",
"team_id",
"COALESCE(channel_id, '')",
"COALESCE(created_by, '')",
"COALESCE(modified_by, '')",
"type",
"COALESCE(title, '')",
"COALESCE(description, '')",
"COALESCE(icon, '')",
"COALESCE(show_description, false)",
"COALESCE(is_template, false)",
"template_version",
"COALESCE(properties, '{}')",
"COALESCE(card_properties, '[]')",
"COALESCE(column_calculations, '{}')",
"COALESCE(create_at, 0)",
"COALESCE(update_at, 0)",
"COALESCE(delete_at, 0)",
}
return fields
}
var boardMemberFields = []string{
"board_id",
"user_id",
"roles",
"scheme_admin",
"scheme_editor",
"scheme_commenter",
"scheme_viewer",
}
func (s *SQLStore) boardsFromRows(rows *sql.Rows) ([]*model.Board, error) {
boards := []*model.Board{}
for rows.Next() {
var board model.Board
var propertiesBytes []byte
var cardPropertiesBytes []byte
var columnCalculationsBytes []byte
err := rows.Scan(
&board.ID,
&board.TeamID,
&board.ChannelID,
&board.CreatedBy,
&board.ModifiedBy,
&board.Type,
&board.Title,
&board.Description,
&board.Icon,
&board.ShowDescription,
&board.IsTemplate,
&board.TemplateVersion,
&propertiesBytes,
&cardPropertiesBytes,
&columnCalculationsBytes,
&board.CreateAt,
&board.UpdateAt,
&board.DeleteAt,
)
if err != nil {
s.logger.Error("boardsFromRows scan error", mlog.Err(err))
return nil, err
}
err = json.Unmarshal(propertiesBytes, &board.Properties)
if err != nil {
s.logger.Error("board properties unmarshal error", mlog.Err(err))
return nil, err
}
err = json.Unmarshal(cardPropertiesBytes, &board.CardProperties)
if err != nil {
s.logger.Error("board card properties unmarshal error", mlog.Err(err))
return nil, err
}
err = json.Unmarshal(columnCalculationsBytes, &board.ColumnCalculations)
if err != nil {
s.logger.Error("board column calculation unmarshal error", mlog.Err(err))
return nil, err
}
boards = append(boards, &board)
}
return boards, nil
}
func (s *SQLStore) boardMembersFromRows(rows *sql.Rows) ([]*model.BoardMember, error) {
boardMembers := []*model.BoardMember{}
for rows.Next() {
var boardMember model.BoardMember
err := rows.Scan(
&boardMember.BoardID,
&boardMember.UserID,
&boardMember.Roles,
&boardMember.SchemeAdmin,
&boardMember.SchemeEditor,
&boardMember.SchemeCommenter,
&boardMember.SchemeViewer,
)
if err != nil {
return nil, err
}
boardMembers = append(boardMembers, &boardMember)
}
return boardMembers, nil
}
func (s *SQLStore) boardMemberHistoryEntriesFromRows(rows *sql.Rows) ([]*model.BoardMemberHistoryEntry, error) {
boardMemberHistoryEntries := []*model.BoardMemberHistoryEntry{}
for rows.Next() {
var boardMemberHistoryEntry model.BoardMemberHistoryEntry
err := rows.Scan(
&boardMemberHistoryEntry.BoardID,
&boardMemberHistoryEntry.UserID,
&boardMemberHistoryEntry.Action,
&boardMemberHistoryEntry.InsertAt,
)
if err != nil {
return nil, err
}
boardMemberHistoryEntries = append(boardMemberHistoryEntries, &boardMemberHistoryEntry)
}
return boardMemberHistoryEntries, nil
}
func (s *SQLStore) getBoardByCondition(db sq.BaseRunner, conditions ...interface{}) (*model.Board, error) {
boards, err := s.getBoardsByCondition(db, conditions...)
if err != nil {
return nil, err
}
return boards[0], nil
}
func (s *SQLStore) getBoardsByCondition(db sq.BaseRunner, conditions ...interface{}) ([]*model.Board, error) {
query := s.getQueryBuilder(db).
Select(boardFields("")...).
From(s.tablePrefix + "boards")
for _, c := range conditions {
query = query.Where(c)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`getBoardsByCondition ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
boards, err := s.boardsFromRows(rows)
if err != nil {
return nil, err
}
if len(boards) == 0 {
return nil, sql.ErrNoRows
}
return boards, nil
}
func (s *SQLStore) getBoard(db sq.BaseRunner, boardID string) (*model.Board, error) {
return s.getBoardByCondition(db, sq.Eq{"id": boardID})
}
func (s *SQLStore) getBoardsForUserAndTeam(db sq.BaseRunner, userID, teamID string) ([]*model.Board, error) {
query := s.getQueryBuilder(db).
Select(boardFields("b.")...).
From(s.tablePrefix + "boards as b").
Join(s.tablePrefix + "board_members as bm on b.id=bm.board_id").
Where(sq.Eq{"b.team_id": teamID}).
Where(sq.Eq{"bm.user_id": userID}).
Where(sq.Eq{"b.is_template": false})
rows, err := query.Query()
if err != nil {
s.logger.Error(`getBoardsForUserAndTeam ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.boardsFromRows(rows)
}
func (s *SQLStore) insertBoard(db sq.BaseRunner, board *model.Board, userID string) (*model.Board, error) {
propertiesBytes, err := json.Marshal(board.Properties)
if err != nil {
s.logger.Error(
"failed to marshal board.Properties",
mlog.String("board_id", board.ID),
mlog.String("board.Properties", fmt.Sprintf("%v", board.Properties)),
mlog.Err(err),
)
return nil, err
}
cardPropertiesBytes, err := json.Marshal(board.CardProperties)
if err != nil {
s.logger.Error(
"failed to marshal board.CardProperties",
mlog.String("board_id", board.ID),
mlog.String("board.CardProperties", fmt.Sprintf("%v", board.CardProperties)),
mlog.Err(err),
)
return nil, err
}
columnCalculationsBytes, err := json.Marshal(board.ColumnCalculations)
if err != nil {
s.logger.Error(
"failed to marshal board.ColumnCalculations",
mlog.String("board_id", board.ID),
mlog.String("board.ColumnCalculations", fmt.Sprintf("%v", board.ColumnCalculations)),
mlog.Err(err),
)
return nil, err
}
existingBoard, err := s.getBoard(db, board.ID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
insertQuery := s.getQueryBuilder(db).Insert("").
Columns(boardFields("")...)
now := utils.GetMillis()
insertQueryValues := map[string]interface{}{
"id": board.ID,
"team_id": board.TeamID,
"channel_id": board.ChannelID,
"created_by": board.CreatedBy,
"modified_by": userID,
"type": board.Type,
"title": board.Title,
"description": board.Description,
"icon": board.Icon,
"show_description": board.ShowDescription,
"is_template": board.IsTemplate,
"template_version": board.TemplateVersion,
"properties": propertiesBytes,
"card_properties": cardPropertiesBytes,
"column_calculations": columnCalculationsBytes,
"create_at": board.CreateAt,
"update_at": now,
"delete_at": board.DeleteAt,
}
if existingBoard != nil {
query := s.getQueryBuilder(db).Update(s.tablePrefix+"boards").
Where(sq.Eq{"id": board.ID}).
Set("modified_by", userID).
Set("type", board.Type).
Set("title", board.Title).
Set("description", board.Description).
Set("icon", board.Icon).
Set("show_description", board.ShowDescription).
Set("is_template", board.IsTemplate).
Set("template_version", board.TemplateVersion).
Set("properties", propertiesBytes).
Set("card_properties", cardPropertiesBytes).
Set("column_calculations", columnCalculationsBytes).
Set("update_at", now).
Set("delete_at", board.DeleteAt)
if _, err := query.Exec(); err != nil {
s.logger.Error(`InsertBoard error occurred while updating existing board`, mlog.String("boardID", board.ID), mlog.Err(err))
return nil, err
}
} else {
insertQueryValues["created_by"] = userID
insertQueryValues["create_at"] = now
insertQueryValues["update_at"] = now
query := insertQuery.SetMap(insertQueryValues).Into(s.tablePrefix + "boards")
if _, err := query.Exec(); err != nil {
return nil, err
}
}
// writing board history
query := insertQuery.SetMap(insertQueryValues).Into(s.tablePrefix + "boards_history")
if _, err := query.Exec(); err != nil {
s.logger.Error("failed to insert board history", mlog.String("board_id", board.ID), mlog.Err(err))
return nil, err
}
return s.getBoard(db, board.ID)
}
func (s *SQLStore) patchBoard(db sq.BaseRunner, boardID string, boardPatch *model.BoardPatch, userID string) (*model.Board, error) {
existingBoard, err := s.getBoard(db, boardID)
if err != nil {
return nil, err
}
if existingBoard == nil {
return nil, BoardNotFoundErr{boardID}
}
board := boardPatch.Patch(existingBoard)
return s.insertBoard(db, board, userID)
}
func (s *SQLStore) deleteBoard(db sq.BaseRunner, boardID, userID string) error {
now := utils.GetMillis()
board, err := s.getBoard(db, boardID)
if err != nil {
return err
}
propertiesBytes, err := json.Marshal(board.Properties)
if err != nil {
return err
}
cardPropertiesBytes, err := json.Marshal(board.CardProperties)
if err != nil {
return err
}
columnCalculationsBytes, err := json.Marshal(board.ColumnCalculations)
if err != nil {
return err
}
insertQueryValues := map[string]interface{}{
"id": board.ID,
"team_id": board.TeamID,
"channel_id": board.ChannelID,
"created_by": board.CreatedBy,
"modified_by": userID,
"type": board.Type,
"title": board.Title,
"description": board.Description,
"icon": board.Icon,
"show_description": board.ShowDescription,
"is_template": board.IsTemplate,
"template_version": board.TemplateVersion,
"properties": propertiesBytes,
"card_properties": cardPropertiesBytes,
"column_calculations": columnCalculationsBytes,
"create_at": board.CreateAt,
"update_at": now,
"delete_at": now,
}
// writing board history
insertQuery := s.getQueryBuilder(db).Insert("").
Columns(boardHistoryFields()...)
query := insertQuery.SetMap(insertQueryValues).Into(s.tablePrefix + "boards_history")
if _, err := query.Exec(); err != nil {
return err
}
deleteQuery := s.getQueryBuilder(db).
Delete(s.tablePrefix + "boards").
Where(sq.Eq{"id": boardID}).
Where(sq.Eq{"COALESCE(team_id, '0')": board.TeamID})
if _, err := deleteQuery.Exec(); err != nil {
return err
}
return nil
}
func (s *SQLStore) insertBoardWithAdmin(db sq.BaseRunner, board *model.Board, userID string) (*model.Board, *model.BoardMember, error) {
newBoard, err := s.insertBoard(db, board, userID)
if err != nil {
return nil, nil, err
}
bm := &model.BoardMember{
BoardID: newBoard.ID,
UserID: newBoard.CreatedBy,
SchemeAdmin: true,
SchemeEditor: true,
}
nbm, err := s.saveMember(db, bm)
if err != nil {
return nil, nil, err
}
return newBoard, nbm, nil
}
func (s *SQLStore) saveMember(db sq.BaseRunner, bm *model.BoardMember) (*model.BoardMember, error) {
queryValues := map[string]interface{}{
"board_id": bm.BoardID,
"user_id": bm.UserID,
"roles": "",
"scheme_admin": bm.SchemeAdmin,
"scheme_editor": bm.SchemeEditor,
"scheme_commenter": bm.SchemeCommenter,
"scheme_viewer": bm.SchemeViewer,
}
oldMember, err := s.getMemberForBoard(db, bm.BoardID, bm.UserID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
query := s.getQueryBuilder(db).
Insert(s.tablePrefix + "board_members").
SetMap(queryValues)
if s.dbType == model.MysqlDBType {
query = query.Suffix(
"ON DUPLICATE KEY UPDATE scheme_admin = ?, scheme_editor = ?, scheme_commenter = ?, scheme_viewer = ?",
bm.SchemeAdmin, bm.SchemeEditor, bm.SchemeCommenter, bm.SchemeViewer)
} else {
query = query.Suffix(
`ON CONFLICT (board_id, user_id)
DO UPDATE SET scheme_admin = EXCLUDED.scheme_admin, scheme_editor = EXCLUDED.scheme_editor,
scheme_commenter = EXCLUDED.scheme_commenter, scheme_viewer = EXCLUDED.scheme_viewer`,
)
}
if _, err := query.Exec(); err != nil {
return nil, err
}
if oldMember == nil {
addToMembersHistory := s.getQueryBuilder(db).
Insert(s.tablePrefix+"board_members_history").
Columns("board_id", "user_id", "action", "insert_at").
Values(bm.BoardID, bm.UserID, "created", model.GetMillis())
if _, err := addToMembersHistory.Exec(); err != nil {
return nil, err
}
}
return bm, nil
}
func (s *SQLStore) deleteMember(db sq.BaseRunner, boardID, userID string) error {
deleteQuery := s.getQueryBuilder(db).
Delete(s.tablePrefix + "board_members").
Where(sq.Eq{"board_id": boardID}).
Where(sq.Eq{"user_id": userID})
result, err := deleteQuery.Exec()
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected > 0 {
addToMembersHistory := s.getQueryBuilder(db).
Insert(s.tablePrefix+"board_members_history").
Columns("board_id", "user_id", "action", "insert_at").
Values(boardID, userID, "deleted", model.GetMillis())
if _, err := addToMembersHistory.Exec(); err != nil {
return err
}
}
return nil
}
func (s *SQLStore) getMemberForBoard(db sq.BaseRunner, boardID, userID string) (*model.BoardMember, error) {
query := s.getQueryBuilder(db).
Select(boardMemberFields...).
From(s.tablePrefix + "board_members").
Where(sq.Eq{"board_id": boardID}).
Where(sq.Eq{"user_id": userID})
rows, err := query.Query()
if err != nil {
s.logger.Error(`getMemberForBoard ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
members, err := s.boardMembersFromRows(rows)
if err != nil {
return nil, err
}
if len(members) == 0 {
return nil, sql.ErrNoRows
}
return members[0], nil
}
func (s *SQLStore) getMembersForUser(db sq.BaseRunner, userID string) ([]*model.BoardMember, error) {
query := s.getQueryBuilder(db).
Select(boardMemberFields...).
From(s.tablePrefix + "board_members").
Where(sq.Eq{"user_id": userID})
rows, err := query.Query()
if err != nil {
s.logger.Error(`getMembersForUser ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
members, err := s.boardMembersFromRows(rows)
if err != nil {
return nil, err
}
return members, nil
}
func (s *SQLStore) getMembersForBoard(db sq.BaseRunner, boardID string) ([]*model.BoardMember, error) {
query := s.getQueryBuilder(db).
Select(boardMemberFields...).
From(s.tablePrefix + "board_members").
Where(sq.Eq{"board_id": boardID})
rows, err := query.Query()
if err != nil {
s.logger.Error(`getMembersForBoard ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.boardMembersFromRows(rows)
}
// searchBoardsForUserAndTeam returns all boards that match with the
// term that are either private and which the user is a member of, or
// they're open, regardless of the user membership.
// Search is case-insensitive.
func (s *SQLStore) searchBoardsForUserAndTeam(db sq.BaseRunner, term, userID, teamID string) ([]*model.Board, error) {
query := s.getQueryBuilder(db).
Select(boardFields("b.")...).
Distinct().
From(s.tablePrefix + "boards as b").
LeftJoin(s.tablePrefix + "board_members as bm on b.id=bm.board_id").
Where(sq.Eq{"b.team_id": teamID}).
Where(sq.Eq{"b.is_template": false}).
Where(sq.Or{
sq.Eq{"b.type": model.BoardTypeOpen},
sq.And{
sq.Eq{"b.type": model.BoardTypePrivate},
sq.Eq{"bm.user_id": userID},
},
})
if term != "" {
// break search query into space separated words
// and search for each word.
// This should later be upgraded to industrial-strength
// word tokenizer, that uses much more than space
// to break words.
conditions := sq.Or{}
for _, word := range strings.Split(strings.TrimSpace(term), " ") {
conditions = append(conditions, sq.Like{"lower(b.title)": "%" + strings.ToLower(word) + "%"})
}
query = query.Where(conditions)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`searchBoardsForUserAndTeam ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.boardsFromRows(rows)
}
func (s *SQLStore) getBoardHistory(db sq.BaseRunner, boardID string, opts model.QueryBlockHistoryOptions) ([]*model.Board, error) {
var order string
if opts.Descending {
order = " DESC "
}
query := s.getQueryBuilder(db).
Select(boardHistoryFields()...).
From(s.tablePrefix + "boards_history").
Where(sq.Eq{"id": boardID}).
OrderBy("insert_at " + order + ", update_at" + order)
if opts.BeforeUpdateAt != 0 {
query = query.Where(sq.Lt{"update_at": opts.BeforeUpdateAt})
}
if opts.AfterUpdateAt != 0 {
query = query.Where(sq.Gt{"update_at": opts.AfterUpdateAt})
}
if opts.Limit != 0 {
query = query.Limit(opts.Limit)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`getBoardHistory ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.boardsFromRows(rows)
}
func (s *SQLStore) getBoardMemberHistory(db sq.BaseRunner, boardID, userID string, limit uint64) ([]*model.BoardMemberHistoryEntry, error) {
query := s.getQueryBuilder(db).
Select("board_id", "user_id", "action", "insert_at").
From(s.tablePrefix + "board_members_history").
Where(sq.Eq{"board_id": boardID}).
Where(sq.Eq{"user_id": userID}).
OrderBy("insert_at DESC")
if limit > 0 {
query = query.Limit(limit)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`getBoardMemberHistory ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
memberHistory, err := s.boardMemberHistoryEntriesFromRows(rows)
if err != nil {
return nil, err
}
return memberHistory, nil
}