From e9bad085ed7a0fb9dc3851beafce3ab6abbbc215 Mon Sep 17 00:00:00 2001
From: artaasadi <arta-c@kaytu.io>
Date: Sun, 29 Dec 2024 21:10:54 +0100
Subject: [PATCH] fix: preload query in fetching views in db

---
 pkg/cloudql/sdk/extra/view-sync/view_sync.go | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/pkg/cloudql/sdk/extra/view-sync/view_sync.go b/pkg/cloudql/sdk/extra/view-sync/view_sync.go
index 5c7f8a297..5f77b6542 100644
--- a/pkg/cloudql/sdk/extra/view-sync/view_sync.go
+++ b/pkg/cloudql/sdk/extra/view-sync/view_sync.go
@@ -2,6 +2,7 @@ package view_sync
 
 import (
 	"context"
+	"gorm.io/gorm/clause"
 	"os"
 	"strings"
 	"sync"
@@ -132,7 +133,7 @@ func (v *ViewSync) updateViewsInDatabase(ctx context.Context, selfClient *steamp
 
 	var queryViews []models.QueryView
 
-	err := metadataClient.DB().Model(&models.QueryView{}).Find(&queryViews).Error
+	err := metadataClient.DB().Model(&models.QueryView{}).Preload(clause.Associations).Preload("Query.Parameters").Find(&queryViews).Error
 	if err != nil {
 		v.logger.Error("Error fetching query views from metadata", zap.Error(err))
 		v.logger.Sync()
@@ -176,6 +177,11 @@ initLoop:
 				continue
 			}
 
+			if view.Query == nil || view.Query.QueryToExecute == "" {
+				v.logger.Error("Error fetching view from database", zap.String("view", view.ID))
+				continue
+			}
+
 			query := "CREATE MATERIALIZED VIEW IF NOT EXISTS " + view.ID + " AS " + view.Query.QueryToExecute
 			_, err = selfClient.GetConnection().Exec(ctx, query)
 			if err != nil && strings.Contains(err.Error(), "SQLSTATE 42P01") {