Django mysql tuple index out of range - mysql

My views.py looks like following:
#api_view(('GET',))
def save_progress_for_particular_user(request, exerciseId, rating):
#view to call stored proc that stores the progress for a particular user
#save_progress(user_id,exercise_id,rating,date)
result=Exercise_progress_model.save_progress_for_particular_user(
request.user.id, exerciseId, rating, datetime.date.today())
serializer = ExerciseProgressSerializer(result, many=True)
return Response(serializer.data)
My models.py looks like following:
class Exercise_progress_model(models.Model):
# Model that will be rendered on the UI
#Field for storing intensity level
INTENSITY_LEVEL_CHOICES = (
(1, 'Really simple'),
(2, 'Rather Simple'),
(3, 'Simple'),
(4, 'Okay'),
(5, 'Difficult'),
(6, 'Rather Difficult'),
(7, 'Really Difficult'),
)
intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)
#Field for storing progress
progress = models.IntegerField(default='0')
#Field for storing exercise type
EXERCISE_TYPE_CHOICES = (
(1, 'Best stretch'),
(2, 'Butterfly reverse'),
(3, 'Squat row'),
(4, 'Plank'),
(5, 'Push up'),
(6, 'Side plank'),
(7, 'Squat'),
)
exercise_id = models.IntegerField(choices=EXERCISE_TYPE_CHOICES)
#Field for storing current date
current_date = models.DateField()
#Field for storing user rating
user_rating = models.IntegerField(default='0')
# static method to save progress for a particular user
#staticmethod
def save_progress_for_particular_user(user_id, exercise_id, rating, date):
# create a cursor
cur = connection.cursor()
# execute the stored procedure passing in
# search_string as a parameter
cur.callproc('save_exercise_state', [user_id, exercise_id, rating, date,])
# grab the results
result = cur.fetchall()
cur.close()
User_progress_list = []
for row in result:
Epm = Exercise_progress_model()
Epm.intensity_level=row[0]
Epm.progress=row[1]
Epm.exercise_id=row[2]
Epm.user_rating=row[3]
Epm.current_date=row[4]
User_progress_list.append(Epm)
return User_progress_list
My serializers.py looks like following:
class ExerciseProgressSerializer(serializers.Serializer):
intensity_level = serializers.IntegerField(required=True)
progress = serializers.IntegerField(required=True)
exercise_type = serializers.IntegerField(required=True)
user_rating = serializers.IntegerField(required=True)
current_date = serializers.DateField()
My stored procedure looks like following:
delimiter //
CREATE PROCEDURE save_exercise_state(
p_user_id int, p_exercise_id int, p_rating int, p_date date
)
BEGIN
DECLARE lv_current_intensity, lv_progress, lv_final_intensity int;
DECLARE lv_date date;
select intensity_level into lv_current_intensity
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select progress into lv_progress
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select current_date into lv_date
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select lv_progress, lv_current_intensity, lv_date;
If lv_date=p_date then
select "OK";
end if;
if p_rating=0 then
set lv_progress=lv_progress;
elseif p_rating=1 then
if lv_progress=3 then
set lv_progress=0;
if lv_current_intensity = 7 then
set lv_final_intensity = 7;
else
set lv_final_intensity = lv_current_intensity + 1;
end if;
else
if lv_current_intensity=7 then
set lv_progress=0;
set lv_final_intensity=lv_current_intensity;
else
set lv_progress=lv_progress+1;
set lv_final_intensity=lv_current_intensity;
end if;
end if;
elseif p_rating =-1 then
if lv_progress=0 then
if lv_current_intensity = 1 then
set lv_final_intensity = 1;
set lv_progress=0;
else
set lv_final_intensity = lv_current_intensity - 1;
set lv_progress=3;
end if;
else
set lv_progress=lv_progress-1;
set lv_final_intensity=lv_current_intensity;
end if;
end if;
Update demo_exercise_state
SET progress = lv_progress,
intensity_level = lv_final_intensity,
`current_date` = p_date,
user_rating = p_rating
WHERE user_id = p_user_id AND exercise_id = p_exercise_id;
SELECT intensity_level, progress, exercise_id, user_rating , current_date
FROM demo_exercise_state
WHERE user_id = p_user_id AND exercise_id = p_exercise_id AND user_rating=p_rating;
END
//
Screenshot of the result of executing this proc for
call save_exercise_state(4,1,1,curdate()); is as following
When I call this view I get tuple index out of range error for the line Epm.user_rating=row[3].
What is the reason for this? Is there any workaround?

Related

Mysql integrity error 1452 on insert

select * from memory_games_game; gives me following table:
select * from memory_games_game_state;gives me following table:
I have a stored proc as bellow:
delimiter //
CREATE PROCEDURE get_game_by_user_id(
p_user_id int, p_game_id int
)
BEGIN
insert into memory_games_game_state(user_id, game_id, level, progress)
SELECT 24 as user_id,
game.game_type as game_id,
1 as level,
0 as progress
FROM memory_games_game game
left outer join memory_games_game_state gameState on
game.game_type=gameState.game_id and
gameState.user_id=24
where game.level=1 and gameState.user_id is null;
if p_game_id = -1 then
SELECT gameState.level, game_type, `current_date`
FROM memory_games_game game join memory_games_game_state gameState on
game.game_type=gameState.game_id and
gameState.user_id=24 and
game.level=gameState.level;
else
SELECT gameState.level, game_type, `current_date`
FROM memory_games_game game join memory_games_game_state gameState on
game.game_type=gameState.game_id and
gameState.user_id=p_user_id and
game.level=gameState.level
WHERE game_type=12;
end if;
END
//
The first insert inserts the records into memory_games_game_statetable.
This insert is successful for game_id from 8 to 11 however, it fails for 12 with following error:
I am able to insert records in table memory_games_gamefor game_type 12 which is nothing but game_id in the other table i.e. memory_games_game_state
What's going wrong?
UPDATE:
My django models:
class Game(models.Model):
#Field for storing game type
GAME_TYPE_CHOICES = (
(8, 'Simon Game'),
(9, 'Pinpoint reaction'),
(10, 'Loslassen'),
(11, 'Word pair'),
(12, 'Wortschatz')
)
game_type = models.IntegerField(choices=GAME_TYPE_CHOICES)
level = models.IntegerField(default='1')
#This helps to print in admin interface
def __str__(self):
return u"%s level %s" % (self.get_game_type_display(), self.level)
class Game_state(models.Model):
game = models.ForeignKey(Game, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
level = models.IntegerField(default='1')
progress = models.IntegerField(default='0')
current_date = models.DateField(auto_now=True)
class Game_state_ui_model(models.Model):
GAME_TYPE_CHOICES = (
(8, 'Simon Game'),
(9, 'Pinpoint reaction'),
(10, 'Loslassen'),
(11, 'Word pair'),
(12, 'Wortschatz')
)
game_type = models.IntegerField(choices=GAME_TYPE_CHOICES)
level = models.IntegerField()
user_id = models.IntegerField(default='0')
current_date = models.DateField(auto_now=True)
# static method to fetch games for a paricular user
#staticmethod
def fetch_games(user_id, game_id):
print("Fetching games in model")
# create a cursor
cur = connection.cursor()
# execute the stored procedure passing in
# search_string as a parameter
cur.callproc('get_game_by_user_id', [user_id, game_id,])
# grab the results
results = cur.fetchall()
cur.close()
Game_state_list=[]
for row in results:
print("Get game", row)
Gs = Game_state_ui_model()
Gs.level=row[0]
Gs.game_type=row[1]
Gs.current_date=row[2]
Game_state_list.append(Gs)
return Game_state_list
As the error states, game_id references memory_games_game.id; NOT memory_games_game.game_type.
The thinking that "game_type 12 which is nothing but game_id in the other table i.e. memory_games_game_state" is incorrect.
You need a row in memory_games_game with id = 12.
I dropped all the tables and did migration again, which somehow solved the problem. I didn't change anything else.

Error 1111 when calling a stored function

So I found a post that talked about putting certain logic tests behind HAVING instead of WHERE. What am I missing that's still tripping error 1111?
DROP PROCEDURE IF EXISTS ELO;
DELIMITER //
CREATE PROCEDURE ELO()
BEGIN
-- declares...
label1: WHILE xGame <= max(games.game_id) DO
SELECT games.game_id, games.game_type, games.date, games.home_team, games.away_team, games.runs0, games.runs1
FROM games
WHERE games.game_id = xGame
HAVING (games.game_type = 0 OR games.game_type = 3)
INTO #id, #ty, #d, #home, #away, #homeR, #awayR;
SET startHomeELO = (SELECT team_elo.team_id, team_elo.date, team_elo.elo FROM team_elo WHERE team_id = home HAVING min(d - team_elo.date));
SET startAwayELO = (SELECT team_elo.team_id, team_elo.date, team_elo.elo FROM team_elo WHERE team_id = away HAVING min(d - team_elo.date));
SET eloDiff = abs((startHomeELO + 25) - startAwayELO);
SET homeELO = (startHomeELO + (40*power(runDiff, (1/3)) * (homeWin - (1/(power(10, (eloDiff/400)) + 1)))));
SET awayELO = (startAwayELO + (40*power(runDiff, (1/3)) * (awayWin - (1/(power(10, (eloDiff/400)) + 1)))));
INSERT INTO team_elo (team_id, game_id, date, elo) VALUES (home, id, d, homeELO);
INSERT INTO team_elo (team_id, game_id, date, elo) VALUES (away, id, d, awayELO);
SET xGame = xGame + 1;
END WHILE label1;
END; //
CALL ELO();
You need to do a separate query to get the maximum ID:
INT maxId;
SELECT MAX(game_id) INTO maxId
FROM games;
label1: while xGame <= maxId DO
...
END WHILE label1;

error message not displaying on mysql stored procedure

I am trying to validate something but It always returns a success result. I wonder what's wrong with my codes.
INSERT INTO playlist_details (playlist_id,filename,image_id,transition,timeframe,userid,update_date)
VALUES (i_playlistid,i_filename,i_imageid, i_transition, i_time, i_userid,i_date);
SELECT booking_id INTO v_booking_id FROM staging_table WHERE playlist_id = i_playlistid LIMIT 1;
SELECT num_of_spots INTO v_spots FROM booking_sum WHERE booking_id = v_booking_id;
SET v_allowed_time = v_spots * 30;
IF ((SELECT SUM(timeframe) FROM playlist_details WHERE playlist_id = i_playlistid) > v_allowed_time) THEN
SET o_success = FALSE;
SET o_message = 'You exceeded the time allowed with your booking';
SELECT playlist_id,filename,image_id,transition,timeframe,userid FROM playlist_details
WHERE userid = i_userid;
ELSE
SELECT playlist_id,filename,image_id,transition,timeframe,userid FROM playlist_details
WHERE userid = i_userid;
SET o_success = TRUE;
SET o_message = 'Success';
END IF;

Tips on a Stored procedure with CONVERT , Split functions

I'm studying a stored procedure with the following variable that I need to decipher, ResponseRange :
**#ResponseRange VARCHAR(64) = null,**
then later we have:
IF (#ResponseRange is not null)
BEGIN
INSERT
INTO #tempLK_ResponseStatuses
SELECT CONVERT(INT, val) FROM dbo.Split(#ResponseRange, ',')
END
IF (#ClientResponseRange is not null)
BEGIN
INSERT
INTO #tempClientLK_ResponseStatuses
SELECT CONVERT(INT, val) FROM dbo.Split(#ClientResponseRange, ',')
END
What is happening with the line
SELECT CONVERT(INT, val) FROM dbo.Split(....)
I believe all the above corresponds to the code from the Web-page CS file, of which here's a sample:
new ResponseGroup() {
ID = (int) ResponseStatusGroups.Completes,
Code = 1,
Label = "Completes",
ResponseCodes = null,
ClientResponseCodes = "10,11,12,13,14,15,16,17,18,19"
},
new ResponseGroup() {
ID = (int) ResponseStatusGroups.OverQuota,
Code = 2,
Label = "Over Quota",
ResponseCodes = "40,41,42,43,44,45,46,47,48,49",
ClientResponseCodes = "40,41,42,43,44,45,46,47,48,49"

MySQL Stored Procedure with IF/THEN/ELSE

I have a MySQL stored procedure and in it, the following WHILE statement.
I have confirmed that #RowCnt is 1, and #MaxRows is 6090, however after further debugging, I realized that the WHILE statement is going through a single iteration and not continuing; so I'm hoping to have some light shed on what could possibly be causing this.
Full disclosure: I ported this from SQL Server to a MySQL stored procedure, something I have never taken on before. (meaning SQL Server, porting OR stored procedures..)
WHILE #RowCnt <= #MaxRows DO
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF ( ((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId) ) THEN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
ELSE
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd, ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002', #saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID, timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength, #lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END IF;
SET #RowCnt = #RowCnt+1;
END WHILE;
Try This Construct
WHILE (#RowCnt <= #MaxRows)
BEGIN
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF (((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId))
BEGIN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
END
ELSE
BEGIN
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd,ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002',#saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID,timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength,#lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END
SET #RowCnt = #RowCnt+1;
END