From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ayu Ishii <ayui@chromium.org>
Date: Fri, 15 Jul 2022 13:20:47 +0000
Subject: When applying the omit-ORDER-BY optimization, defer deleting the AST
 of the deleted ORDER BY clause until after code generation ends.

FossilOrigin-Name: b88d6c4b814ec4166ec50f32a2f10d7857df05414c0048c1234ab290a273e50c
(cherry picked from commit 9dde91f61386e4fc53eb95b6cbd26bf30521225f)
Bug: 1343348
Change-Id: Id677f72166c00a05f95c25438230f4b1d40f4d4d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/deps/sqlite/+/3764026
Reviewed-by: Austin Sullivan <asully@chromium.org>
Commit-Queue: Ayu Ishii <ayui@chromium.org>
Reviewed-by: Joshua Bell <jsbell@chromium.org>

diff --git a/amalgamation/sqlite3.c b/amalgamation/sqlite3.c
index b903fd1c4440a9f83b2ec513c5f38ec21b9557ef..9b9c2d727e7b0c21a03353aba6b4725e7d7c1633 100644
--- a/amalgamation/sqlite3.c
+++ b/amalgamation/sqlite3.c
@@ -140765,7 +140765,9 @@ SQLITE_PRIVATE int sqlite3Select(
     ){
       SELECTTRACE(0x100,pParse,p,
                 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
-      sqlite3ExprListDelete(db, pSub->pOrderBy);
+      sqlite3ParserAddCleanup(pParse,
+         (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
+         pSub->pOrderBy);
       pSub->pOrderBy = 0;
     }
 
diff --git a/amalgamation_dev/sqlite3.c b/amalgamation_dev/sqlite3.c
index 88b0bcb38e8e2f45aa449b5895bfc29baa543fea..94222875ff2d1e47370e3fa766003cfb0f8dc015 100644
--- a/amalgamation_dev/sqlite3.c
+++ b/amalgamation_dev/sqlite3.c
@@ -140778,7 +140778,9 @@ SQLITE_PRIVATE int sqlite3Select(
     ){
       SELECTTRACE(0x100,pParse,p,
                 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
-      sqlite3ExprListDelete(db, pSub->pOrderBy);
+      sqlite3ParserAddCleanup(pParse,
+         (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
+         pSub->pOrderBy);
       pSub->pOrderBy = 0;
     }
 
diff --git a/src/select.c b/src/select.c
index d6d6097401a748bf1b8268deb8a66daf23f4ea7c..ad7635f76c29c7a7206920947f9ea21626faf0ab 100644
--- a/src/select.c
+++ b/src/select.c
@@ -6518,7 +6518,9 @@ int sqlite3Select(
     ){
       SELECTTRACE(0x100,pParse,p,
                 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
-      sqlite3ExprListDelete(db, pSub->pOrderBy);
+      sqlite3ParserAddCleanup(pParse,
+         (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
+         pSub->pOrderBy);
       pSub->pOrderBy = 0;
     }
 
