about summary refs log tree commit diff
path: root/db_actions.go
blob: 4e878501acc4d86518a2a9531afbd27df8f6b5a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// db_actions defines actions on the database
// Copyright (C) 2019 Emile Hansmaennel
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"database/sql"
	"encoding/csv"
	"fmt"
	"git.darknebu.la/GalaxySimulator/structs"
	_ "github.com/lib/pq"
	"io"
	"io/ioutil"
	"log"
	"strconv"
	"strings"
	"time"
)

const (
	DBUSER    = "postgres"
	DBNAME    = "postgres"
	DBSSLMODE = "disable"
)

// connectToDB returns a pointer to an sql database writing to the database
func connectToDB() *sql.DB {
	connStr := fmt.Sprintf("user=%s dbname=%s sslmode=%s", DBUSER, DBNAME, DBSSLMODE)
	db := dbConnect(connStr)
	return db
}

// dbConnect connects to a PostgreSQL database
func dbConnect(connStr string) *sql.DB {
	// connect to the database
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatalf("[ E ] connection: %v", err)
	}

	return db
}

// newTree creates a new tree with the given width
func newTree(width float64) {
	// get the current max root id
	query := fmt.Sprintf("SELECT COALESCE(max(root_id), 0) FROM nodes")
	var currentMaxRootID int64
	err := db.QueryRow(query).Scan(&currentMaxRootID)
	if err != nil {
		log.Fatalf("[ E ] max root id query: %v\n\t\t\t query: %s\n", err, query)
	}

	// build the query creating a new node
	query = fmt.Sprintf("INSERT INTO nodes (box_width, root_id, box_center, depth, isleaf) VALUES (%f, %d, '{0, 0}', 0, TRUE)", width, currentMaxRootID+1)

	// execute the query
	_, err = db.Query(query)
	if err != nil {
		log.Fatalf("[ E ] insert new node query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// insertStar inserts the given star into the stars table and the nodes table tree
func insertStar(star structs.Star2D, index int64) {
	start := time.Now()
	// insert the star into the stars table
	starID := insertIntoStars(star)

	// get the root node id
	query := fmt.Sprintf("SELECT node_id FROM nodes WHERE root_id=%d", index)
	var id int64
	err := db.QueryRow(query).Scan(&id)
	if err != nil {
		log.Fatalf("[ E ] Get root node id query: %v\n\t\t\t query: %s\n", err, query)
	}

	// insert the star into the tree (using it's ID) starting at the root
	insertIntoTree(starID, id)
	elapsedTime := time.Since(start)
	log.Printf("\t\t\t\t\t %s", elapsedTime)
}

// insertIntoStars inserts the given star into the stars table
func insertIntoStars(star structs.Star2D) int64 {
	// unpack the star
	x := star.C.X
	y := star.C.Y
	vx := star.V.X
	vy := star.V.Y
	m := star.M

	// build the request query
	query := fmt.Sprintf("INSERT INTO stars (x, y, vx, vy, m) VALUES (%f, %f, %f, %f, %f) RETURNING star_id", x, y, vx, vy, m)

	// execute the query
	var starID int64
	err := db.QueryRow(query).Scan(&starID)
	if err != nil {
		log.Fatalf("[ E ] insert query: %v\n\t\t\t query: %s\n", err, query)
	}

	return starID
}

// insert into tree inserts the given star into the tree starting at the node with the given node id
func insertIntoTree(starID int64, nodeID int64) {
	//starRaw := getStar(starID)
	//nodeCenter := getBoxCenter(nodeID)
	//nodeWidth := getBoxWidth(nodeID)
	//log.Printf("[   ] \t Inserting star %v into the node (c: %v, w: %v)", starRaw, nodeCenter, nodeWidth)

	// There exist four cases:
	//                    | Contains a Star | Does not Contain a Star |
	// ------------------ + --------------- + ----------------------- +
	// Node is a Leaf     | Impossible      | insert into node        |
	//                    |                 | subdivide               |
	// ------------------ + --------------- + ----------------------- +
	// Node is not a Leaf | insert preexist | insert into the subtree |
	//                    | insert new      |                         |
	// ------------------ + --------------- + ----------------------- +

	// get the node with the given nodeID
	// find out if the node contains a star or not
	containsStar := containsStar(nodeID)

	// find out if the node is a leaf
	isLeaf := isLeaf(nodeID)

	// if the node is a leaf and contains a star
	// subdivide the tree
	// insert the preexisting star into the correct subtree
	// insert the new star into the subtree
	if isLeaf == true && containsStar == true {
		//log.Printf("Case 1, \t %v \t %v", nodeWidth, nodeCenter)
		subdivide(nodeID)
		//tree := printTree(nodeID)

		// Stage 1: Inserting the blocking star
		blockingStarID := getStarID(nodeID)                               // get the id of the star blocking the node
		blockingStar := getStar(blockingStarID)                           // get the actual star
		blockingStarQuadrant := quadrant(blockingStar, nodeID)            // find out in which quadrant it belongs
		quadrantNodeID := getQuadrantNodeID(nodeID, blockingStarQuadrant) // get the nodeID of that quadrant
		insertIntoTree(blockingStarID, quadrantNodeID)                    // insert the star into that node
		removeStarFromNode(nodeID)                                        // remove the blocking star from the node it was blocking

		// Stage 1: Inserting the actual star
		star := getStar(starID)                                  // get the actual star
		starQuadrant := quadrant(star, nodeID)                   // find out in which quadrant it belongs
		quadrantNodeID = getQuadrantNodeID(nodeID, starQuadrant) // get the nodeID of that quadrant
		insertIntoTree(starID, nodeID)
	}

	// if the node is a leaf and does not contain a star
	// insert the star into the node and subdivide it
	if isLeaf == true && containsStar == false {
		//log.Printf("Case 2, \t %v \t %v", nodeWidth, nodeCenter)
		directInsert(starID, nodeID)
	}

	// if the node is not a leaf and contains a star
	// insert the preexisting star into the correct subtree
	// insert the new star into the subtree
	if isLeaf == false && containsStar == true {
		//log.Printf("Case 3, \t %v \t %v", nodeWidth, nodeCenter)
		// Stage 1: Inserting the blocking star
		blockingStarID := getStarID(nodeID)                               // get the id of the star blocking the node
		blockingStar := getStar(blockingStarID)                           // get the actual star
		blockingStarQuadrant := quadrant(blockingStar, nodeID)            // find out in which quadrant it belongs
		quadrantNodeID := getQuadrantNodeID(nodeID, blockingStarQuadrant) // get the nodeID of that quadrant
		insertIntoTree(blockingStarID, quadrantNodeID)                    // insert the star into that node
		removeStarFromNode(nodeID)                                        // remove the blocking star from the node it was blocking

		// Stage 1: Inserting the actual star
		star := getStar(blockingStarID)                          // get the actual star
		starQuadrant := quadrant(star, nodeID)                   // find out in which quadrant it belongs
		quadrantNodeID = getQuadrantNodeID(nodeID, starQuadrant) // get the nodeID of that quadrant
		insertIntoTree(starID, nodeID)
	}

	// if the node is not a leaf and does not contain a star
	// insert the new star into the according subtree
	if isLeaf == false && containsStar == false {
		//log.Printf("Case 4, \t %v \t %v", nodeWidth, nodeCenter)
		star := getStar(starID)                                   // get the actual star
		starQuadrant := quadrant(star, nodeID)                    // find out in which quadrant it belongs
		quadrantNodeID := getQuadrantNodeID(nodeID, starQuadrant) // get the if of that quadrant
		insertIntoTree(starID, quadrantNodeID)                    // insert the star into that quadrant
	}
}

// containsStar returns true if the node with the given id contains a star and returns false if not.
func containsStar(id int64) bool {
	var starID int64

	query := fmt.Sprintf("SELECT star_id FROM nodes WHERE node_id=%d", id)
	err := db.QueryRow(query).Scan(&starID)
	if err != nil {
		log.Fatalf("[ E ] containsStar query: %v\n\t\t\t query: %s\n", err, query)
	}

	if starID != 0 {
		return true
	}

	return false
}

// isLeaf returns true if the node with the given id is a leaf
func isLeaf(nodeID int64) bool {
	var isLeaf bool

	query := fmt.Sprintf("SELECT COALESCE(isleaf, FALSE) FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&isLeaf)
	if err != nil {
		log.Fatalf("[ E ] isLeaf query: %v\n\t\t\t query: %s\n", err, query)
	}

	if isLeaf == true {
		return true
	}

	return false
}

// directInsert inserts the star with the given ID into the given node inside of the given database
func directInsert(starID int64, nodeID int64) {
	// build the query
	query := fmt.Sprintf("UPDATE nodes SET star_id=%d WHERE node_id=%d", starID, nodeID)

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] directInsert query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// subdivide subdivides the given node creating four child nodes
func subdivide(nodeID int64) {
	boxWidth := getBoxWidth(nodeID)
	boxCenter := getBoxCenter(nodeID)
	originalDepth := getNodeDepth(nodeID)

	// calculate the new positions
	newPosX := boxCenter[0] + (boxWidth / 2)
	newPosY := boxCenter[1] + (boxWidth / 2)
	newNegX := boxCenter[0] - (boxWidth / 2)
	newNegY := boxCenter[1] - (boxWidth / 2)
	newWidth := boxWidth / 2

	// create new news with those positions
	newNodeIDA := newNode(newPosX, newPosY, newWidth, originalDepth+1)
	newNodeIDB := newNode(newPosX, newNegY, newWidth, originalDepth+1)
	newNodeIDC := newNode(newNegX, newPosY, newWidth, originalDepth+1)
	newNodeIDD := newNode(newNegX, newNegY, newWidth, originalDepth+1)

	// Update the subtrees of the parent node

	// build the query
	query := fmt.Sprintf("UPDATE nodes SET subnode='{%d, %d, %d, %d}', isleaf=FALSE WHERE node_id=%d", newNodeIDA, newNodeIDB, newNodeIDC, newNodeIDD, nodeID)

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] subdivide query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// getBoxWidth gets the width of the box from the node width the given id
func getBoxWidth(nodeID int64) float64 {
	var boxWidth float64

	query := fmt.Sprintf("SELECT box_width FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&boxWidth)
	if err != nil {
		log.Fatalf("[ E ] getBoxWidth query: %v\n\t\t\t query: %s\n", err, query)
	}

	return boxWidth
}

// getBoxWidth gets the center of the box from the node width the given id
func getBoxCenter(nodeID int64) []float64 {
	var boxCenterX, boxCenterY []uint8

	query := fmt.Sprintf("SELECT box_center[1], box_center[2] FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&boxCenterX, &boxCenterY)
	if err != nil {
		log.Fatalf("[ E ] getBoxCenter query: %v\n\t\t\t query: %s\n", err, query)
	}

	x, parseErr := strconv.ParseFloat(string(boxCenterX), 64)
	y, parseErr := strconv.ParseFloat(string(boxCenterX), 64)

	if parseErr != nil {
		log.Fatalf("[ E ] parse boxCenter: %v\n\t\t\t query: %s\n", err, query)
		log.Fatalf("[ E ] parse boxCenter: (%f, %f)\n", x, y)
	}

	boxCenterFloat := []float64{x, y}

	return boxCenterFloat
}

// newNode Inserts a new node into the database with the given parameters
func newNode(x float64, y float64, width float64, depth int64) int64 {
	// build the query creating a new node
	query := fmt.Sprintf("INSERT INTO nodes (box_center, box_width, depth, isleaf) VALUES ('{%f, %f}', %f, %d, TRUE) RETURNING node_id", x, y, width, depth)

	var nodeID int64

	// execute the query
	err := db.QueryRow(query).Scan(&nodeID)
	if err != nil {
		log.Fatalf("[ E ] newNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	return nodeID
}

// getStarID returns the id of the star inside of the node with the given ID
func getStarID(nodeID int64) int64 {
	// get the star id from the node
	var starID int64
	query := fmt.Sprintf("SELECT star_id FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&starID)
	if err != nil {
		log.Fatalf("[ E ] getStarID id query: %v\n\t\t\t query: %s\n", err, query)
	}

	return starID
}

// deleteAll Stars deletes all the rows in the stars table
func deleteAllStars() {
	// build the query creating a new node
	query := "DELETE FROM stars WHERE TRUE"

	// execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] deleteAllStars query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// deleteAll Stars deletes all the rows in the nodes table
func deleteAllNodes() {
	// build the query creating a new node
	query := "DELETE FROM nodes WHERE TRUE"

	// execute the query
	_, err := db.Query(query)
	if err != nil {
		log.Fatalf("[ E ] deleteAllStars query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// getNodeDepth returns the depth of the given node in the tree
func getNodeDepth(nodeID int64) int64 {
	// build the query
	query := fmt.Sprintf("SELECT depth FROM nodes WHERE node_id=%d", nodeID)

	var depth int64

	// Execute the query
	err := db.QueryRow(query).Scan(&depth)
	if err != nil {
		log.Fatalf("[ E ] getNodeDepth query: %v \n\t\t\t query: %s\n", err, query)
	}

	return depth
}

// quadrant returns the quadrant into which the given star belongs
func quadrant(star structs.Star2D, nodeID int64) int64 {
	// get the center of the node the star is in
	center := getBoxCenter(nodeID)
	centerX := center[0]
	centerY := center[1]

	if star.C.X > centerX {
		if star.C.Y > centerY {
			// North East condition
			return 1
		}
		// South East condition
		return 3
	}

	if star.C.Y > centerY {
		// North West condition
		return 0
	}
	// South West condition
	return 2
}

// getQuadrantNodeID returns the id of the requested child-node
// Example: if a parent has four children and quadrant 0 is requested, the function returns the north east child id
func getQuadrantNodeID(parentNodeID int64, quadrant int64) int64 {
	var a, b, c, d []uint8

	// get the star from the stars table
	query := fmt.Sprintf("SELECT subnode[1], subnode[2], subnode[3], subnode[4] FROM nodes WHERE node_id=%d", parentNodeID)
	err := db.QueryRow(query).Scan(&a, &b, &c, &d)
	if err != nil {
		log.Fatalf("[ E ] getQuadrantNodeID star query: %v \n\t\t\tquery: %s\n", err, query)
	}

	returnA, _ := strconv.ParseInt(string(a), 10, 64)
	returnB, _ := strconv.ParseInt(string(b), 10, 64)
	returnC, _ := strconv.ParseInt(string(c), 10, 64)
	returnD, _ := strconv.ParseInt(string(d), 10, 64)

	switch quadrant {
	case 0:
		return returnA
	case 1:
		return returnB
	case 2:
		return returnC
	case 3:
		return returnD
	}

	return -1
}

// getStar returns the star with the given ID from the stars table
func getStar(starID int64) structs.Star2D {
	var x, y, vx, vy, m float64

	// get the star from the stars table
	query := fmt.Sprintf("SELECT x, y, vx, vy, m FROM stars WHERE star_id=%d", starID)
	err := db.QueryRow(query).Scan(&x, &y, &vx, &vy, &m)
	if err != nil {
		log.Fatalf("[ E ] getStar query: %v \n\t\t\tquery: %s\n", err, query)
	}

	star := structs.Star2D{
		C: structs.Vec2{
			X: x,
			Y: y,
		},
		V: structs.Vec2{
			X: vx,
			Y: vy,
		},
		M: m,
	}

	return star
}

// getStarMass returns the mass if the star with the given ID
func getStarMass(starID int64) float64 {
	var mass float64

	// get the star from the stars table
	query := fmt.Sprintf("SELECT m FROM stars WHERE star_id=%d", starID)
	err := db.QueryRow(query).Scan(&mass)
	if err != nil {
		log.Fatalf("[ E ] getStarMass query: %v \n\t\t\tquery: %s\n", err, query)
	}

	return mass
}

// getNodeTotalMass returns the total mass of the node with the given ID and its children
func getNodeTotalMass(nodeID int64) float64 {
	var mass float64

	// get the star from the stars table
	query := fmt.Sprintf("SELECT total_mass FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&mass)
	if err != nil {
		log.Fatalf("[ E ] getStarMass query: %v \n\t\t\tquery: %s\n", err, query)
	}

	return mass
}

// removeStarFromNode removes the star from the node with the given ID
func removeStarFromNode(nodeID int64) {
	// build the query
	query := fmt.Sprintf("UPDATE nodes SET star_id=0 WHERE node_id=%d", nodeID)

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] removeStarFromNode query: %v\n\t\t\t query: %s\n", err, query)
	}
}

// getListOfStarsGo returns the list of stars in go struct format
func getListOfStarsGo() []structs.Star2D {
	// build the query
	query := fmt.Sprintf("SELECT * FROM stars")

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] removeStarFromNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	var starList []structs.Star2D

	// iterate over the returned rows
	for rows.Next() {

		var star_id int64
		var x, y, vx, vy, m float64
		scanErr := rows.Scan(&star_id, &x, &y, &vx, &vy, &m)
		if scanErr != nil {
			log.Fatalf("[ E ] scan error: %v", scanErr)
		}

		star := structs.Star2D{
			C: structs.Vec2{
				X: x,
				Y: y,
			},
			V: structs.Vec2{
				X: vx,
				Y: vy,
			},
			M: m,
		}

		starList = append(starList, star)
	}

	return starList
}

// getListOfStarsCsv returns an array of strings containing the coordinates of all the stars in the stars table
func getListOfStarsCsv() []string {
	// build the query
	query := fmt.Sprintf("SELECT * FROM stars")

	// Execute the query
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		log.Fatalf("[ E ] removeStarFromNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	var starList []string

	// iterate over the returned rows
	for rows.Next() {

		var star_id int64
		var x, y, vx, vy, m float64
		scanErr := rows.Scan(&star_id, &x, &y, &vx, &vy, &m)
		if scanErr != nil {
			log.Fatalf("[ E ] scan error: %v", scanErr)
		}

		row := fmt.Sprintf("%d, %f, %f, %f, %f, %f", star_id, x, y, vx, vy, m)
		starList = append(starList, row)
	}

	return starList
}

// insertList inserts all the stars in the given .csv into the stars and nodes table
func insertList(filename string) {
	// open the file
	content, readErr := ioutil.ReadFile(filename)
	if readErr != nil {
		panic(readErr)
	}

	in := string(content)
	reader := csv.NewReader(strings.NewReader(in))

	// insert all the stars into the db
	for {
		record, err := reader.Read()
		if err == io.EOF {
			log.Println("EOF")
			break
		}
		if err != nil {
			log.Println("insertListErr")
			panic(err)
		}

		x, _ := strconv.ParseFloat(record[0], 64)
		y, _ := strconv.ParseFloat(record[1], 64)

		star := structs.Star2D{
			C: structs.Vec2{
				X: x / 100000,
				Y: y / 100000,
			},
			V: structs.Vec2{
				X: 0,
				Y: 0,
			},
			M: 1000,
		}

		fmt.Printf("Inserting (%f, %f)\n", star.C.X, star.C.Y)
		insertStar(star, 1)
	}
}

// getRootNodeID gets a tree index and returns the nodeID of its root node
func getRootNodeID(index int64) int64 {
	var nodeID int64

	query := fmt.Sprintf("SELECT node_id FROM nodes WHERE root_id=%d", index)
	err := db.QueryRow(query).Scan(&nodeID)
	if err != nil {
		log.Fatalf("[ E ] getRootNodeID query: %v\n\t\t\t query: %s\n", err, query)
	}

	return nodeID
}

// updateTotalMass gets a tree index and returns the nodeID of the trees root node
func updateTotalMass(index int64) {
	rootNodeID := getRootNodeID(index)
	log.Printf("RootID: %d", rootNodeID)
	updateTotalMassNode(rootNodeID)
}

// updateTotalMassNode updates the total mass of the given node
func updateTotalMassNode(nodeID int64) float64 {
	var totalmass float64

	// get the subnode ids
	var subnode [4]int64

	query := fmt.Sprintf("SELECT subnode[1], subnode[2], subnode[3], subnode[4] FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&subnode[0], &subnode[1], &subnode[2], &subnode[3])
	if err != nil {
		log.Fatalf("[ E ] updateTotalMassNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	// iterate over all subnodes updating their total masses
	for _, subnodeID := range subnode {
		fmt.Println("----------------------------")
		fmt.Printf("SubdnodeID: %d\n", subnodeID)
		if subnodeID != 0 {
			totalmass += updateTotalMassNode(subnodeID)
		} else {
			// get the starID for getting the star mass
			starID := getStarID(nodeID)
			fmt.Printf("StarID: %d\n", starID)
			if starID != 0 {
				mass := getStarMass(starID)
				log.Printf("starID=%d \t mass: %f", starID, mass)
				totalmass += mass
			}

			// break, this stops a star from being counted multiple (4) times
			break
		}
		fmt.Println("----------------------------")
	}

	query = fmt.Sprintf("UPDATE nodes SET total_mass=%f WHERE node_id=%d", totalmass, nodeID)
	_, err = db.Query(query)
	if err != nil {
		log.Fatalf("[ E ] insert total_mass query: %v\n\t\t\t query: %s\n", err, query)
	}

	fmt.Printf("nodeID: %d \t totalMass: %f\n", nodeID, totalmass)

	return totalmass
}

// updateCenterOfMass recursively updates the center of mass of all the nodes starting at the node with the given
// root index
func updateCenterOfMass(index int64) {
	rootNodeID := getRootNodeID(index)
	log.Printf("RootID: %d", rootNodeID)
	updateCenterOfMassNode(rootNodeID)
}

// updateCenterOfMassNode updates the center of mass of the node with the given nodeID recursively
func updateCenterOfMassNode(nodeID int64) structs.Vec2 {
	var nominatorX float64
	var deNominatorX float64
	var nominatorY float64
	var deNominatorY float64

	var centerOfMassX float64
	var centerOfMassY float64
	var centerOfMass structs.Vec2

	// get the subnode ids
	var subnode [4]int64

	query := fmt.Sprintf("SELECT subnode[1], subnode[2], subnode[3], subnode[4] FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&subnode[0], &subnode[1], &subnode[2], &subnode[3])
	if err != nil {
		log.Fatalf("[ E ] updateCenterOfMassNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	// iterate over all subnodes updating their total masses
	for _, subnodeID := range subnode {
		fmt.Println("----------------------------")
		fmt.Printf("SubdnodeID: %d\n", subnodeID)
		if subnodeID != 0 {
			nominatorX += updateCenterOfMassNode(subnodeID).X * getNodeTotalMass(subnodeID)
			deNominatorX += getNodeTotalMass(subnodeID)
			nominatorY += updateCenterOfMassNode(subnodeID).Y * getNodeTotalMass(subnodeID)
			deNominatorY += getNodeTotalMass(subnodeID)
		} else {
			log.Printf("Getting the starID using the nodeID %d", nodeID)
			starID := getStarID(nodeID)
			if starID != 0 {
				// as the cell contains only a single star, the center of mass is the position of that single star
				centerOfMass.X = getStar(starID).C.X
				centerOfMass.Y = getStar(starID).C.Y
				break
			}
		}
		fmt.Println("----------------------------")
	}

	// if the center of mass has not been set yet, set it
	if centerOfMass == (structs.Vec2{0, 0}) {
		if deNominatorX != 0 || deNominatorY != 0 {
			centerOfMassX = nominatorX / deNominatorX
			centerOfMassY = nominatorY / deNominatorY
		}
		centerOfMass = structs.Vec2{centerOfMassX, centerOfMassY}
	}

	query = fmt.Sprintf("UPDATE nodes SET center_of_mass='{%f, %f}' WHERE node_id=%d", centerOfMassX, centerOfMassY, nodeID)
	_, err = db.Query(query)
	if err != nil {
		log.Fatalf("[ E ] insert center_of_mass query: %v\n\t\t\t query: %s\n", err, query)
	}

	fmt.Printf("nodeID: %d \t totalMass: %v\n", nodeID, centerOfMass)

	return centerOfMass
}

// genForestTree generates a forest representation of the tree with the given index
func genForestTree(index int64) string {
	rootNodeID := getRootNodeID(index)
	return genForestTreeNode(rootNodeID)
}

// genForestTreeNodes returns a sub-representation of a given node in forest format
func genForestTreeNode(nodeID int64) string {
	var returnString string

	// get the subnode ids
	var subnode [4]int64

	query := fmt.Sprintf("SELECT subnode[1], subnode[2], subnode[3], subnode[4] FROM nodes WHERE node_id=%d", nodeID)
	err := db.QueryRow(query).Scan(&subnode[0], &subnode[1], &subnode[2], &subnode[3])
	if err != nil {
		log.Fatalf("[ E ] updateTotalMassNode query: %v\n\t\t\t query: %s\n", err, query)
	}

	returnString += "["

	// iterate over all subnodes updating their total masses
	for _, subnodeID := range subnode {
		if subnodeID != 0 {
			returnString += genForestTreeNode(subnodeID)
		} else {

			// get the starID for getting the star mass
			starID := getStarID(nodeID)
			returnString += fmt.Sprintf("[%d]", starID)
			// break, this stops a star from being counted multiple (4) times
			break
		}
	}

	returnString += "]"

	return returnString
}