AddSubSession creates a sub-session and links it to the parent.
(ctx context.Context, parentSessionID string, subSession *Session)
| 1078 | |
| 1079 | // AddSubSession creates a sub-session and links it to the parent. |
| 1080 | func (s *SQLiteSessionStore) AddSubSession(ctx context.Context, parentSessionID string, subSession *Session) error { |
| 1081 | if parentSessionID == "" || subSession.ID == "" { |
| 1082 | return ErrEmptyID |
| 1083 | } |
| 1084 | |
| 1085 | tx, err := s.db.BeginTx(ctx, nil) |
| 1086 | if err != nil { |
| 1087 | return err |
| 1088 | } |
| 1089 | defer func() { |
| 1090 | _ = tx.Rollback() |
| 1091 | }() |
| 1092 | |
| 1093 | // 1. Set parent_id on sub-session |
| 1094 | subSession.ParentID = parentSessionID |
| 1095 | |
| 1096 | // 2. Insert sub-session as a new session row |
| 1097 | if err := s.addSessionTx(ctx, tx, subSession); err != nil { |
| 1098 | return fmt.Errorf("inserting sub-session: %w", err) |
| 1099 | } |
| 1100 | |
| 1101 | // 3. Recursively add all items from the sub-session |
| 1102 | for i, item := range subSession.Messages { |
| 1103 | if err := s.addItemTx(ctx, tx, subSession.ID, i, item); err != nil { |
| 1104 | return fmt.Errorf("inserting sub-session item %d: %w", i, err) |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | // 4. Add reference in parent's items |
| 1109 | _, err = tx.ExecContext(ctx, |
| 1110 | `INSERT INTO session_items (session_id, position, item_type, subsession_id) |
| 1111 | VALUES (?, (SELECT COALESCE(MAX(position), -1) + 1 FROM session_items WHERE session_id = ?), 'subsession', ?)`, |
| 1112 | parentSessionID, parentSessionID, subSession.ID) |
| 1113 | if err != nil { |
| 1114 | return fmt.Errorf("inserting subsession reference: %w", err) |
| 1115 | } |
| 1116 | |
| 1117 | return tx.Commit() |
| 1118 | } |
| 1119 | |
| 1120 | // addSessionTx inserts a session within a transaction. |
| 1121 | func (s *SQLiteSessionStore) addSessionTx(ctx context.Context, tx *sql.Tx, session *Session) error { |