Repository: mindsdb/mindsdb

Issue:
[Bug]: Mysql API - Forecasting query to timeseries predictor works only if HORIZON > 1
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Current Behavior

Forecasting query execution returns:
```
mysql> SELECT * from MYSQL_LOCAL.test_data.covid AS ta JOIN mindsdb.covid_predictor AS tb WHERE ta.state = "CA" AND ta.time > LATEST;
ERROR 1149 (HY000): 'int' object is not subscriptable
``` if predictor has been trained with HORIZON > 1 (2, 3, 4, ...)

### Expected Behavior

Forecasting work must not depend on HORIZON predictor parameter

### Steps To Reproduce

```markdown
1. Launch local mysql server, setup connection and create new database `test_data`
2. Create table covid `create table covid;`
3. Alter table:

alter table covid add column time date;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column adult_icu_bed_utilization float;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column inpatient_beds_utilization float;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column percent_of_inpatients_with_covid float;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column inpatient_bed_covid_utilization float;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column new_case int;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table covid add column pnew_case float;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0
```
4. copy covid data.csv file from benchmark datasets to `/var/lib/mysql-files/`
5. mysql> LOAD DATA INFILE '/var/lib/mysql-files/covid_data.csv' INTO TABLE covid  COLUMNS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
Query OK, 7261 rows affected (0.19 sec)
Records: 7261  Deleted: 0  Skipped: 0  Warnings: 0

6. launch mindsdb and connect to mysql api server
7. create integration to your local database via mindsdb GUI
8. create new ts preodictor:
```
create predictor covid from MYSQL_LOCAL (select * from test_data.covid) as covid_dataset predict pnew_case ORDER BY time GROUP BY state  WINDOW 10 HORIZON 1;
```
9. perform forecast query: 
```
mysql> SELECT * from MYSQL_LOCAL.test_data.covid AS ta JOIN mindsdb.covid AS tb WHERE ta.state = "CA" AND ta.time > LATEST;
ERROR 1149 (HY000): 'int' object is not subscriptable
```
Note that you see `ERROR 1149 (HY000): 'int' object is not subscriptable` error
```


### Anything else?

_No response_


Discussion:
seems like its not even passing HORIZON ->lightwood(nr_predictions) how does mindsdb handle the horizon param

Resolving patch:
diff --git a/mindsdb/api/mysql/mysql_proxy/datahub/datanodes/mindsdb_datanode.py b/mindsdb/api/mysql/mysql_proxy/datahub/datanodes/mindsdb_datanode.py
--- a/mindsdb/api/mysql/mysql_proxy/datahub/datanodes/mindsdb_datanode.py
+++ b/mindsdb/api/mysql/mysql_proxy/datahub/datanodes/mindsdb_datanode.py
@@ -284,7 +284,11 @@ def select(self, table, columns=None, where=None, where_data=None, order_by=None
         if timeseries_settings['is_timeseries'] is True:
             __mdb_make_predictions = set([row.get('__mdb_make_predictions', True) for row in where_data]) == {True}
 
+            predict = model['predict']
             group_by = timeseries_settings['group_by']
+            order_by_column = timeseries_settings['order_by'][0]
+            nr_predictions = timeseries_settings['nr_predictions']
+
             groups = set()
             for row in pred_dicts:
                 groups.add(
@@ -308,10 +312,6 @@ def select(self, table, columns=None, where=None, where_data=None, order_by=None
                         rows_by_groups[group]['rows'].append(row)
                         rows_by_groups[group]['explanations'].append(explanations[row_index])
 
-            predict = model['predict']
-            data_column = timeseries_settings['order_by'][0]
-            nr_predictions = timeseries_settings['nr_predictions']
-
             for group, data in rows_by_groups.items():
                 rows = data['rows']
                 explanations = data['explanations']
@@ -324,13 +324,13 @@ def select(self, table, columns=None, where=None, where_data=None, order_by=None
                     if isinstance(predictions, list) is False:
                         predictions = [predictions]
 
-                    date_values = row[data_column]
+                    date_values = row[order_by_column]
                     if isinstance(date_values, list) is False:
                         date_values = [date_values]
 
                 for i in range(len(rows) - 1):
                     rows[i][predict] = rows[i][predict][0]
-                    rows[i][data_column] = rows[i][data_column][0]
+                    rows[i][order_by_column] = rows[i][order_by_column][0]
                     for col in ('predicted_value', 'confidence', 'confidence_lower_bound', 'confidence_upper_bound'):
                         explanations[i][predict][col] = explanations[i][predict][col][0]
 
@@ -338,15 +338,22 @@ def select(self, table, columns=None, where=None, where_data=None, order_by=None
                 last_explanation = explanations.pop()
                 for i in range(nr_predictions):
                     new_row = copy.deepcopy(last_row)
-                    new_row[predict] = new_row[predict][i]
-                    new_row[data_column] = new_row[data_column][i]
+                    if nr_predictions == 1:
+                        new_row[predict] = new_row[predict]
+                        new_row[order_by_column] = new_row[order_by_column]
+                    else:
+                        new_row[predict] = new_row[predict][i]
+                        new_row[order_by_column] = new_row[order_by_column][i]
                     if '__mindsdb_row_id' in new_row and (i > 0 or __mdb_make_predictions is False):
                         new_row['__mindsdb_row_id'] = None
                     rows.append(new_row)
 
                     new_explanation = copy.deepcopy(last_explanation)
                     for col in ('predicted_value', 'confidence', 'confidence_lower_bound', 'confidence_upper_bound'):
-                        new_explanation[predict][col] = new_explanation[predict][col][i]
+                        if nr_predictions == 1:
+                            new_explanation[predict][col] = new_explanation[predict][col]
+                        else:
+                            new_explanation[predict][col] = new_explanation[predict][col][i]
                     if i != 0:
                         new_explanation[predict]['anomaly'] = None
                         new_explanation[predict]['truth'] = None
@@ -362,14 +369,14 @@ def select(self, table, columns=None, where=None, where_data=None, order_by=None
             for i in range(len(pred_dicts)):
                 original_target_values[f'{predict}_original'].append(explanations[i][predict].get('truth', None))
 
-            if model['dtypes'][data_column] == dtype.date:
+            if model['dtypes'][order_by_column] == dtype.date:
                 for row in pred_dicts:
-                    if isinstance(row[data_column], (int, float)):
-                        row[data_column] = str(datetime.fromtimestamp(row[data_column]).date())
-            elif model['dtypes'][data_column] == dtype.datetime:
+                    if isinstance(row[order_by_column], (int, float)):
+                        row[order_by_column] = str(datetime.fromtimestamp(row[order_by_column]).date())
+            elif model['dtypes'][order_by_column] == dtype.datetime:
                 for row in pred_dicts:
-                    if isinstance(row[data_column], (int, float)):
-                        row[data_column] = str(datetime.fromtimestamp(row[data_column]))
+                    if isinstance(row[order_by_column], (int, float)):
+                        row[order_by_column] = str(datetime.fromtimestamp(row[order_by_column]))
 
         keys = [x for x in pred_dicts[0] if x in columns]
         min_max_keys = []


Test patch: