// Code generated by modernc.org/undup from the per-target sqlite_*.go files; DO NOT EDIT.

//go:build (freebsd && 386) || (freebsd && arm) || (linux && 386) || (linux && arm)

package sqlite3

import (
	"unsafe"

	"modernc.org/libc"
)

type Tfd_mask = uint32

type Tregister_t = int32

type Ttm = struct {
	Ftm_sec    int32
	Ftm_min    int32
	Ftm_hour   int32
	Ftm_mday   int32
	Ftm_mon    int32
	Ftm_year   int32
	Ftm_wday   int32
	Ftm_yday   int32
	Ftm_isdst  int32
	Ftm_gmtoff int32
	Ftm_zone   uintptr
}

// C documentation
//
//	/*
//	** Copy nPage pages from the source b-tree to the destination.
//	*/
func Xsqlite3_backup_step(tls *libc.TLS, p uintptr, nPage int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var bCloseTrans, destMode, ii, nDestTruncate, nSrcPage, pgszDest, pgszSrc, ratio, rc, v2 int32
	var iEnd, iOff, iSize Ti64
	var iPg, iSrcPg, iSrcPg1 TPgno
	var pDest, pDestPager, pFile, pSrcPager, zData, v1 uintptr
	var v3 bool
	var v6 int64
	var _ /* nDstPage at bp+4 */ int32
	var _ /* pPg at bp+8 */ uintptr
	var _ /* pSrcPg at bp+0 */ uintptr
	var _ /* pSrcPg at bp+12 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = bCloseTrans, destMode, iEnd, iOff, iPg, iSize, iSrcPg, iSrcPg1, ii, nDestTruncate, nSrcPage, pDest, pDestPager, pFile, pSrcPager, pgszDest, pgszSrc, ratio, rc, zData, v1, v2, v3, v6
	destMode = 0 /* Destination journal mode */
	pgszSrc = 0  /* Source page size */
	pgszDest = 0 /* Destination page size */
	Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrcDb)).Fmutex)
	_sqlite3BtreeEnter(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)
	if (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb != 0 {
		Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb)).Fmutex)
	}
	rc = (*Tsqlite3_backup)(unsafe.Pointer(p)).Frc
	if !(_isFatalError(tls, rc) != 0) {
		pSrcPager = _sqlite3BtreePager(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc) /* Source pager */
		pDest = uintptr(0)                                                               /* Dest btree */
		pDestPager = uintptr(0)                                                          /* Iterator variable */
		nSrcPage = -int32(1)                                                             /* Size of source db in pages */
		bCloseTrans = 0                                                                  /* True if src db requires unlocking */
		/* If the source pager is currently in a write-transaction, return
		 ** SQLITE_BUSY immediately.
		 */
		if (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb != 0 && libc.Int32FromUint8((*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)).FpBt)).FinTransaction) == int32(TRANS_WRITE) {
			rc = int32(SQLITE_BUSY)
		} else {
			rc = SQLITE_OK
		}
		/* If there is no open read-transaction on the source database, open
		 ** one now. If a transaction is opened here, then it will be closed
		 ** before this function exits.
		 */
		if rc == SQLITE_OK && SQLITE_TXN_NONE == _sqlite3BtreeTxnState(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc) {
			rc = _sqlite3BtreeBeginTrans(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc, 0, uintptr(0))
			bCloseTrans = int32(1)
		}
		/* Locate the destination btree and pager. */
		v1 = (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest
		pDest = v1
		if v1 == uintptr(0) {
			pDest = _findBtree(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb, (*Tsqlite3_backup)(unsafe.Pointer(p)).FzDestDb)
		}
		if pDest == uintptr(0) {
			rc = int32(SQLITE_ERROR)
		} else {
			pDestPager = _sqlite3BtreePager(tls, pDest)
		}
		/* If the destination database has not yet been locked (i.e. if this
		 ** is the first call to backup_step() for the current backup operation),
		 ** try to set its page size to the same as the source database. This
		 ** is especially important on ZipVFS systems, as in that case it is
		 ** not possible to create a database file that uses one page size by
		 ** writing to it with another.  */
		if (*Tsqlite3_backup)(unsafe.Pointer(p)).FbDestLocked == 0 && rc == SQLITE_OK && _setDestPgsz(tls, pDest, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc) == int32(SQLITE_NOMEM) {
			rc = int32(SQLITE_NOMEM)
		}
		/* Lock the destination database, if it is not locked already. */
		if v3 = SQLITE_OK == rc && (*Tsqlite3_backup)(unsafe.Pointer(p)).FbDestLocked == 0; v3 {
			v2 = _sqlite3BtreeBeginTrans(tls, pDest, int32(2), p+12)
			rc = v2
		}
		if v3 && SQLITE_OK == v2 {
			(*Tsqlite3_backup)(unsafe.Pointer(p)).FbDestLocked = int32(1)
			(*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest = pDest
		}
		/* Do not allow backup if the destination database is in WAL mode
		 ** and the page sizes are different between source and destination */
		if rc == SQLITE_OK {
			pgszSrc = _sqlite3BtreeGetPageSize(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)
			pgszDest = _sqlite3BtreeGetPageSize(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)
			destMode = _sqlite3PagerGetJournalMode(tls, _sqlite3BtreePager(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest))
			if (destMode == int32(PAGER_JOURNALMODE_WAL) || _sqlite3PagerIsMemdb(tls, pDestPager) != 0) && pgszSrc != pgszDest {
				rc = int32(SQLITE_READONLY)
			}
		}
		/* Now that there is a read-lock on the source database, query the
		 ** source pager for the number of pages in the database.
		 */
		nSrcPage = libc.Int32FromUint32(_sqlite3BtreeLastPage(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc))
		ii = 0
		for {
			if !((nPage < 0 || ii < nPage) && (*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext <= libc.Uint32FromInt32(nSrcPage) && !(rc != 0)) {
				break
			}
			iSrcPg = (*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext                                                                                                                                                /* Source page number */
			if iSrcPg != libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)).FpBt)).FpageSize+libc.Uint32FromInt32(1) { /* Source page object */
				rc = _sqlite3PagerGet(tls, pSrcPager, iSrcPg, bp, int32(PAGER_GET_READONLY))
				if rc == SQLITE_OK {
					rc = _backupOnePage(tls, p, iSrcPg, _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp))), 0)
					_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp)))
				}
			}
			(*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext = (*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext + 1
			goto _4
		_4:
			;
			ii = ii + 1
		}
		if rc == SQLITE_OK {
			(*Tsqlite3_backup)(unsafe.Pointer(p)).FnPagecount = libc.Uint32FromInt32(nSrcPage)
			(*Tsqlite3_backup)(unsafe.Pointer(p)).FnRemaining = libc.Uint32FromInt32(nSrcPage+int32(1)) - (*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext
			if (*Tsqlite3_backup)(unsafe.Pointer(p)).FiNext > libc.Uint32FromInt32(nSrcPage) {
				rc = int32(SQLITE_DONE)
			} else {
				if !((*Tsqlite3_backup)(unsafe.Pointer(p)).FisAttached != 0) {
					_attachBackupObject(tls, p)
				}
			}
		}
		/* Update the schema version field in the destination database. This
		 ** is to make sure that the schema-version really does change in
		 ** the case where the source and destination databases have the
		 ** same schema version.
		 */
		if rc == int32(SQLITE_DONE) {
			if nSrcPage == 0 {
				rc = _sqlite3BtreeNewDb(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)
				nSrcPage = int32(1)
			}
			if rc == SQLITE_OK || rc == int32(SQLITE_DONE) {
				rc = _sqlite3BtreeUpdateMeta(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest, int32(1), (*Tsqlite3_backup)(unsafe.Pointer(p)).FiDestSchema+uint32(1))
			}
			if rc == SQLITE_OK {
				if (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb != 0 {
					_sqlite3ResetAllSchemasOfConnection(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb)
				}
				if destMode == int32(PAGER_JOURNALMODE_WAL) {
					rc = _sqlite3BtreeSetVersion(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest, int32(2))
				}
			}
			if rc == SQLITE_OK {
				/* Set nDestTruncate to the final number of pages in the destination
				 ** database. The complication here is that the destination page
				 ** size may be different to the source page size.
				 **
				 ** If the source page size is smaller than the destination page size,
				 ** round up. In this case the call to sqlite3OsTruncate() below will
				 ** fix the size of the file. However it is important to call
				 ** sqlite3PagerTruncateImage() here so that any pages in the
				 ** destination file that lie beyond the nDestTruncate page mark are
				 ** journalled by PagerCommitPhaseOne() before they are destroyed
				 ** by the file truncation.
				 */
				if pgszSrc < pgszDest {
					ratio = pgszDest / pgszSrc
					nDestTruncate = (nSrcPage + ratio - int32(1)) / ratio
					if nDestTruncate == libc.Int32FromUint32(libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)).FpBt)).FpageSize+libc.Uint32FromInt32(1)) {
						nDestTruncate = nDestTruncate - 1
					}
				} else {
					nDestTruncate = nSrcPage * (pgszSrc / pgszDest)
				}
				if pgszSrc < pgszDest {
					/* If the source page-size is smaller than the destination page-size,
					 ** two extra things may need to happen:
					 **
					 **   * The destination may need to be truncated, and
					 **
					 **   * Data stored on the pages immediately following the
					 **     pending-byte page in the source database may need to be
					 **     copied into the destination database.
					 */
					iSize = int64(pgszSrc) * int64(nSrcPage)
					pFile = _sqlite3PagerFile(tls, pDestPager)
					/* This block ensures that all data required to recreate the original
					 ** database has been stored in the journal for pDestPager and the
					 ** journal synced to disk. So at this point we may safely modify
					 ** the database file in any way, knowing that if a power failure
					 ** occurs, the original database will be reconstructed from the
					 ** journal file.  */
					_sqlite3PagerPagecount(tls, pDestPager, bp+4)
					iPg = libc.Uint32FromInt32(nDestTruncate)
					for {
						if !(rc == SQLITE_OK && iPg <= libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4)))) {
							break
						}
						if iPg != libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)).FpBt)).FpageSize+libc.Uint32FromInt32(1) {
							rc = _sqlite3PagerGet(tls, pDestPager, iPg, bp+8, 0)
							if rc == SQLITE_OK {
								rc = _sqlite3PagerWrite(tls, **(**uintptr)(__ccgo_up(bp + 8)))
								_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 8)))
							}
						}
						goto _5
					_5:
						;
						iPg = iPg + 1
					}
					if rc == SQLITE_OK {
						rc = _sqlite3PagerCommitPhaseOne(tls, pDestPager, uintptr(0), int32(1))
					}
					/* Write the extra pages and truncate the database file as required */
					if int64(_sqlite3PendingByte+pgszDest) < iSize {
						v6 = int64(_sqlite3PendingByte + pgszDest)
					} else {
						v6 = iSize
					}
					iEnd = v6
					iOff = int64(_sqlite3PendingByte + pgszSrc)
					for {
						if !(rc == SQLITE_OK && iOff < iEnd) {
							break
						}
						**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
						iSrcPg1 = libc.Uint32FromInt64(iOff/int64(pgszSrc) + libc.Int64FromInt32(1))
						rc = _sqlite3PagerGet(tls, pSrcPager, iSrcPg1, bp+12, 0)
						if rc == SQLITE_OK {
							zData = _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp + 12)))
							rc = _sqlite3OsWrite(tls, pFile, zData, pgszSrc, iOff)
						}
						_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 12)))
						goto _7
					_7:
						;
						iOff = iOff + int64(pgszSrc)
					}
					if rc == SQLITE_OK {
						rc = _backupTruncateFile(tls, pFile, iSize)
					}
					/* Sync the database file to disk. */
					if rc == SQLITE_OK {
						rc = _sqlite3PagerSync(tls, pDestPager, uintptr(0))
					}
				} else {
					_sqlite3PagerTruncateImage(tls, pDestPager, libc.Uint32FromInt32(nDestTruncate))
					rc = _sqlite3PagerCommitPhaseOne(tls, pDestPager, uintptr(0), 0)
				}
				/* Finish committing the transaction to the destination database. */
				if v3 = SQLITE_OK == rc; v3 {
					v2 = _sqlite3BtreeCommitPhaseTwo(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest, 0)
					rc = v2
				}
				if v3 && SQLITE_OK == v2 {
					rc = int32(SQLITE_DONE)
				}
			}
		}
		/* If bCloseTrans is true, then this function opened a read transaction
		 ** on the source database. Close the read transaction here. There is
		 ** no need to check the return values of the btree methods here, as
		 ** "committing" a read-only transaction cannot fail.
		 */
		if bCloseTrans != 0 {
			_sqlite3BtreeCommitPhaseOne(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc, uintptr(0))
			_sqlite3BtreeCommitPhaseTwo(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc, 0)
		}
		if rc == libc.Int32FromInt32(SQLITE_IOERR)|libc.Int32FromInt32(12)<<libc.Int32FromInt32(8) {
			rc = int32(SQLITE_NOMEM)
		}
		(*Tsqlite3_backup)(unsafe.Pointer(p)).Frc = rc
	}
	if (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb != 0 {
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpDestDb)).Fmutex)
	}
	_sqlite3BtreeLeave(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)
	Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrcDb)).Fmutex)
	return rc
}

func Xsqlite3_bind_double(tls *libc.TLS, pStmt uintptr, i int32, rValue float64) (r int32) {
	var p uintptr
	var rc int32
	_, _ = p, rc
	p = pStmt
	rc = _vdbeUnbind(tls, p, libc.Uint32FromInt32(i-libc.Int32FromInt32(1)))
	if rc == SQLITE_OK {
		/* tag-20240917-01 */
		_sqlite3VdbeMemSetDouble(tls, (*TVdbe)(unsafe.Pointer(p)).FaVar+uintptr(i-int32(1))*40, rValue)
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fmutex)
	}
	return rc
}

func Xsqlite3_bind_int64(tls *libc.TLS, pStmt uintptr, i int32, iValue Tsqlite_int64) (r int32) {
	var p uintptr
	var rc int32
	_, _ = p, rc
	p = pStmt
	rc = _vdbeUnbind(tls, p, libc.Uint32FromInt32(i-libc.Int32FromInt32(1)))
	if rc == SQLITE_OK {
		/* tag-20240917-01 */
		_sqlite3VdbeMemSetInt64(tls, (*TVdbe)(unsafe.Pointer(p)).FaVar+uintptr(i-int32(1))*40, iValue)
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fmutex)
	}
	return rc
}

func Xsqlite3_bind_pointer(tls *libc.TLS, pStmt uintptr, i int32, pPtr uintptr, zPTtype uintptr, __ccgo_fp_xDestructor uintptr) (r int32) {
	var p uintptr
	var rc int32
	_, _ = p, rc
	p = pStmt
	rc = _vdbeUnbind(tls, p, libc.Uint32FromInt32(i-libc.Int32FromInt32(1)))
	if rc == SQLITE_OK {
		/* tag-20240917-01 */
		_sqlite3VdbeMemSetPointer(tls, (*TVdbe)(unsafe.Pointer(p)).FaVar+uintptr(i-int32(1))*40, pPtr, zPTtype, __ccgo_fp_xDestructor)
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fmutex)
	} else {
		if __ccgo_fp_xDestructor != 0 {
			(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xDestructor})))(tls, pPtr)
		}
	}
	return rc
}

func Xsqlite3_bind_zeroblob(tls *libc.TLS, pStmt uintptr, i int32, n int32) (r int32) {
	var p uintptr
	var rc int32
	_, _ = p, rc
	p = pStmt
	rc = _vdbeUnbind(tls, p, libc.Uint32FromInt32(i-libc.Int32FromInt32(1)))
	if rc == SQLITE_OK {
		/* tag-20240917-01 */
		_sqlite3VdbeMemSetZeroBlob(tls, (*TVdbe)(unsafe.Pointer(p)).FaVar+uintptr(i-int32(1))*40, n)
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fmutex)
	}
	return rc
}

// C documentation
//
//	/*
//	** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
//	** set of routines that is invoked for each new database connection, if it
//	** is currently on the list.  If xInit is not on the list, then this
//	** routine is a no-op.
//	**
//	** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
//	** was not on the list.
//	*/
func Xsqlite3_cancel_auto_extension(tls *libc.TLS, __ccgo_fp_xInit uintptr) (r int32) {
	var i, n int32
	var mutex uintptr
	_, _, _ = i, mutex, n
	mutex = _sqlite3MutexAlloc(tls, int32(SQLITE_MUTEX_STATIC_MAIN))
	n = 0
	Xsqlite3_mutex_enter(tls, mutex)
	i = libc.Int32FromUint32(_sqlite3Autoext.FnExt) - int32(1)
	for {
		if !(i >= 0) {
			break
		}
		if **(**uintptr)(__ccgo_up(_sqlite3Autoext.FaExt + uintptr(i)*4)) == __ccgo_fp_xInit {
			_sqlite3Autoext.FnExt = _sqlite3Autoext.FnExt - 1
			**(**uintptr)(__ccgo_up(_sqlite3Autoext.FaExt + uintptr(i)*4)) = **(**uintptr)(__ccgo_up(_sqlite3Autoext.FaExt + uintptr(_sqlite3Autoext.FnExt)*4))
			n = n + 1
			break
		}
		goto _1
	_1:
		;
		i = i - 1
	}
	Xsqlite3_mutex_leave(tls, mutex)
	return n
}

func Xsqlite3_column_value(tls *libc.TLS, pStmt uintptr, i int32) (r uintptr) {
	var pOut, v1 uintptr
	_, _ = pOut, v1
	pOut = _columnMem(tls, pStmt, i)
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pOut)).Fflags)&int32(MEM_Static) != 0 {
		v1 = pOut + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(MEM_Static))
		v1 = pOut + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_Ephem))
	}
	_columnMallocFailure(tls, pStmt)
	return pOut
}

// C documentation
//
//	/*
//	** This API allows applications to modify the global configuration of
//	** the SQLite library at run-time.
//	**
//	** This routine should only be called when there are no outstanding
//	** database connections or memory allocations.  This routine is not
//	** threadsafe.  Failure to heed these warnings can lead to unpredictable
//	** behavior.
//	*/
func Xsqlite3_config(tls *libc.TLS, op int32, va uintptr) (r int32) {
	var ap Tva_list
	var bOpenUri, rc int32
	var mxMmap, szMmap Tsqlite3_int64
	var pLogArg, pVal, xLog uintptr
	_, _, _, _, _, _, _, _ = ap, bOpenUri, mxMmap, pLogArg, pVal, rc, szMmap, xLog
	rc = SQLITE_OK
	/* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
	 ** the SQLite library is in use.  Except, a few selected opcodes
	 ** are allowed.
	 */
	if libc.AtomicLoadPInt32(uintptr(unsafe.Pointer(&_sqlite3Config))+208) != 0 {
		if op < 0 || op > int32(63) || libc.Uint64FromInt32(1)<<op&_mAnytimeConfigOption == uint64(0) {
			return _sqlite3MisuseError(tls, int32(187803))
		}
	}
	ap = va
	switch op {
	/* Mutex configuration options are only available in a threadsafe
	 ** compile.
	 */
	case int32(SQLITE_CONFIG_SINGLETHREAD):
		/* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
		 ** Single-thread. */
		_sqlite3Config.FbCoreMutex = uint8(0) /* Disable mutex on core */
		_sqlite3Config.FbFullMutex = uint8(0) /* Disable mutex on connections */
	case int32(SQLITE_CONFIG_MULTITHREAD):
		/* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
		 ** Multi-thread. */
		_sqlite3Config.FbCoreMutex = uint8(1) /* Enable mutex on core */
		_sqlite3Config.FbFullMutex = uint8(0) /* Disable mutex on connections */
	case int32(SQLITE_CONFIG_SERIALIZED):
		/* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
		 ** Serialized. */
		_sqlite3Config.FbCoreMutex = uint8(1) /* Enable mutex on core */
		_sqlite3Config.FbFullMutex = uint8(1) /* Enable mutex on connections */
	case int32(SQLITE_CONFIG_MUTEX):
		/* Specify an alternative mutex implementation */
		_sqlite3Config.Fmutex = **(**Tsqlite3_mutex_methods)(__ccgo_up(libc.VaUintptr(&ap)))
	case int32(SQLITE_CONFIG_GETMUTEX):
		/* Retrieve the current mutex implementation */
		**(**Tsqlite3_mutex_methods)(__ccgo_up(libc.VaUintptr(&ap))) = _sqlite3Config.Fmutex
	case int32(SQLITE_CONFIG_MALLOC):
		/* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
		 ** single argument which is a pointer to an instance of the
		 ** sqlite3_mem_methods structure. The argument specifies alternative
		 ** low-level memory allocation routines to be used in place of the memory
		 ** allocation routines built into SQLite. */
		_sqlite3Config.Fm = **(**Tsqlite3_mem_methods)(__ccgo_up(libc.VaUintptr(&ap)))
	case int32(SQLITE_CONFIG_GETMALLOC):
		/* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
		 ** single argument which is a pointer to an instance of the
		 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
		 ** filled with the currently defined memory allocation routines. */
		if _sqlite3Config.Fm.FxMalloc == uintptr(0) {
			_sqlite3MemSetDefault(tls)
		}
		**(**Tsqlite3_mem_methods)(__ccgo_up(libc.VaUintptr(&ap))) = _sqlite3Config.Fm
	case int32(SQLITE_CONFIG_MEMSTATUS):
		/* Cannot change at runtime */
		/* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
		 ** single argument of type int, interpreted as a boolean, which enables
		 ** or disables the collection of memory allocation statistics. */
		_sqlite3Config.FbMemstat = libc.VaInt32(&ap)
	case int32(SQLITE_CONFIG_SMALL_MALLOC):
		_sqlite3Config.FbSmallMalloc = libc.Uint8FromInt32(libc.VaInt32(&ap))
	case int32(SQLITE_CONFIG_PAGECACHE):
		/* EVIDENCE-OF: R-18761-36601 There are three arguments to
		 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
		 ** the size of each page cache line (sz), and the number of cache lines
		 ** (N). */
		_sqlite3Config.FpPage = libc.VaUintptr(&ap)
		_sqlite3Config.FszPage = libc.VaInt32(&ap)
		_sqlite3Config.FnPage = libc.VaInt32(&ap)
	case int32(SQLITE_CONFIG_PCACHE_HDRSZ):
		/* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
		 ** a single parameter which is a pointer to an integer and writes into
		 ** that integer the number of extra bytes per page required for each page
		 ** in SQLITE_CONFIG_PAGECACHE. */
		**(**int32)(__ccgo_up(libc.VaUintptr(&ap))) = _sqlite3HeaderSizeBtree(tls) + _sqlite3HeaderSizePcache(tls) + _sqlite3HeaderSizePcache1(tls)
	case int32(SQLITE_CONFIG_PCACHE):
		/* no-op */
	case int32(SQLITE_CONFIG_GETPCACHE):
		/* now an error */
		rc = int32(SQLITE_ERROR)
	case int32(SQLITE_CONFIG_PCACHE2):
		/* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
		 ** single argument which is a pointer to an sqlite3_pcache_methods2
		 ** object. This object specifies the interface to a custom page cache
		 ** implementation. */
		_sqlite3Config.Fpcache2 = **(**Tsqlite3_pcache_methods2)(__ccgo_up(libc.VaUintptr(&ap)))
	case int32(SQLITE_CONFIG_GETPCACHE2):
		/* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
		 ** single argument which is a pointer to an sqlite3_pcache_methods2
		 ** object. SQLite copies of the current page cache implementation into
		 ** that object. */
		if _sqlite3Config.Fpcache2.FxInit == uintptr(0) {
			_sqlite3PCacheSetDefault(tls)
		}
		**(**Tsqlite3_pcache_methods2)(__ccgo_up(libc.VaUintptr(&ap))) = _sqlite3Config.Fpcache2
		break
		/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
		 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
		 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
		fallthrough
	case int32(SQLITE_CONFIG_LOOKASIDE):
		_sqlite3Config.FszLookaside = libc.VaInt32(&ap)
		_sqlite3Config.FnLookaside = libc.VaInt32(&ap)
		break
		/* Record a pointer to the logger function and its first argument.
		 ** The default is NULL.  Logging is disabled if the function pointer is
		 ** NULL.
		 */
		fallthrough
	case int32(SQLITE_CONFIG_LOG):
		xLog = libc.VaUintptr(&ap)
		pLogArg = libc.VaUintptr(&ap)
		libc.AtomicStoreNUintptr(uintptr(unsafe.Pointer(&_sqlite3Config))+236, xLog, libc.Int32FromInt32(__ATOMIC_RELAXED))
		libc.AtomicStoreNUintptr(uintptr(unsafe.Pointer(&_sqlite3Config))+240, pLogArg, libc.Int32FromInt32(__ATOMIC_RELAXED))
		break
		/* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
		 ** can be changed at start-time using the
		 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
		 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
		 */
		fallthrough
	case int32(SQLITE_CONFIG_URI):
		/* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
		 ** argument of type int. If non-zero, then URI handling is globally
		 ** enabled. If the parameter is zero, then URI handling is globally
		 ** disabled. */
		bOpenUri = libc.VaInt32(&ap)
		libc.AtomicStoreNUint8(uintptr(unsafe.Pointer(&_sqlite3Config))+6, libc.Uint8FromInt32(bOpenUri), libc.Int32FromInt32(__ATOMIC_RELAXED))
	case int32(SQLITE_CONFIG_COVERING_INDEX_SCAN):
		/* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
		 ** option takes a single integer argument which is interpreted as a
		 ** boolean in order to enable or disable the use of covering indices for
		 ** full table scans in the query optimizer. */
		_sqlite3Config.FbUseCis = libc.Uint8FromInt32(libc.VaInt32(&ap))
	case int32(SQLITE_CONFIG_MMAP_SIZE):
		/* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
		 ** integer (sqlite3_int64) values that are the default mmap size limit
		 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
		 ** mmap size limit. */
		szMmap = libc.VaInt64(&ap)
		mxMmap = libc.VaInt64(&ap)
		/* EVIDENCE-OF: R-53367-43190 If either argument to this option is
		 ** negative, then that argument is changed to its compile-time default.
		 **
		 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
		 ** silently truncated if necessary so that it does not exceed the
		 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
		 ** compile-time option.
		 */
		if mxMmap < 0 || mxMmap > int64(SQLITE_MAX_MMAP_SIZE) {
			mxMmap = int64(SQLITE_MAX_MMAP_SIZE)
		}
		if szMmap < 0 {
			szMmap = SQLITE_DEFAULT_MMAP_SIZE
		}
		if szMmap > mxMmap {
			szMmap = mxMmap
		}
		_sqlite3Config.FmxMmap = mxMmap
		_sqlite3Config.FszMmap = szMmap
	case int32(SQLITE_CONFIG_PMASZ):
		_sqlite3Config.FszPma = libc.VaUint32(&ap)
	case int32(SQLITE_CONFIG_STMTJRNL_SPILL):
		_sqlite3Config.FnStmtSpill = libc.VaInt32(&ap)
	case int32(SQLITE_CONFIG_MEMDB_MAXSIZE):
		_sqlite3Config.FmxMemdbSize = libc.VaInt64(&ap)
	case int32(SQLITE_CONFIG_ROWID_IN_VIEW):
		pVal = libc.VaUintptr(&ap)
		**(**int32)(__ccgo_up(pVal)) = 0
	default:
		rc = int32(SQLITE_ERROR)
		break
	}
	_ = ap
	return rc
}

// C documentation
//
//	/*
//	** Initialize the operating system interface.
//	**
//	** This routine registers all VFS implementations for unix-like operating
//	** systems.  This routine, and the sqlite3_os_end() routine that follows,
//	** should be the only routines in this file that are visible from other
//	** files.
//	**
//	** This routine is called once during SQLite initialization and by a
//	** single thread.  The memory allocation and mutex subsystems have not
//	** necessarily been initialized when this routine is called, and so they
//	** should not be used.
//	*/
func Xsqlite3_os_init(tls *libc.TLS) (r int32) {
	var i uint32
	_ = i
	/* Double-check that the aSyscall[] array has been constructed
	 ** correctly.  See ticket [bb3a86e890c8e96ab] */
	/* Register all VFSes defined in the aVfs[] array */
	i = uint32(0)
	for {
		if !(i < libc.Uint32FromInt64(352)/libc.Uint32FromInt64(88)) {
			break
		}
		Xsqlite3_vfs_register(tls, uintptr(unsafe.Pointer(&_aVfs))+uintptr(i)*88, libc.BoolInt32(i == uint32(0)))
		goto _1
	_1:
		;
		i = i + 1
	}
	_unixBigLock = _sqlite3MutexAlloc(tls, int32(SQLITE_MUTEX_STATIC_VFS1))
	/* Validate lock assumptions */
	/* Number of available locks */
	/* Start of locking area */
	/* Locks:
	 **    WRITE       UNIX_SHM_BASE      120
	 **    CKPT        UNIX_SHM_BASE+1    121
	 **    RECOVER     UNIX_SHM_BASE+2    122
	 **    READ-0      UNIX_SHM_BASE+3    123
	 **    READ-1      UNIX_SHM_BASE+4    124
	 **    READ-2      UNIX_SHM_BASE+5    125
	 **    READ-3      UNIX_SHM_BASE+6    126
	 **    READ-4      UNIX_SHM_BASE+7    127
	 **    DMS         UNIX_SHM_BASE+8    128
	 */
	/* Byte offset of the deadman-switch */
	/* Initialize temp file dir array. */
	_unixTempFileInit(tls)
	return SQLITE_OK
}

/*
 ** The following macro defines an initializer for an sqlite3_vfs object.
 ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
 ** to the "finder" function.  (pAppData is a pointer to a pointer because
 ** silly C90 rules prohibit a void* from being cast to a function pointer
 ** and so we have to go through the intermediate pointer to avoid problems
 ** when compiling with -pedantic-errors on GCC.)
 **
 ** The FINDER parameter to this macro is the name of the pointer to the
 ** finder-function.  The finder-function returns a pointer to the
 ** sqlite_io_methods object that implements the desired locking
 ** behaviors.  See the division above that contains the IOMETHODS
 ** macro for addition information on finder-functions.
 **
 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
 ** object.  But the "autolockIoFinder" available on MacOSX does a little
 ** more than that; it looks at the filesystem type that hosts the
 ** database file and tries to choose an locking method appropriate for
 ** that filesystem time.
 */

// C documentation
//
//	/*
//	** This function is called from within a pre-update callback to retrieve
//	** a field of the row currently being updated or inserted.
//	*/
func Xsqlite3_preupdate_new(tls *libc.TLS, db uintptr, iIdx int32, ppValue uintptr) (r int32) {
	var iStore, rc, v1 int32
	var p, pData, pMem, pUnpack uintptr
	_, _, _, _, _, _, _ = iStore, p, pData, pMem, pUnpack, rc, v1
	rc = SQLITE_OK
	iStore = 0
	p = (*Tsqlite3)(unsafe.Pointer(db)).FpPreUpdate
	if !(p != 0) || (*TPreUpdate)(unsafe.Pointer(p)).Fop == int32(SQLITE_DELETE) {
		rc = _sqlite3MisuseError(tls, int32(96071))
		goto preupdate_new_out
	}
	if (*TPreUpdate)(unsafe.Pointer(p)).FpPk != 0 && (*TPreUpdate)(unsafe.Pointer(p)).Fop != int32(SQLITE_UPDATE) {
		iStore = _sqlite3TableColumnToIndex(tls, (*TPreUpdate)(unsafe.Pointer(p)).FpPk, iIdx)
	} else {
		if iIdx >= int32((*TTable)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).FpTab)).FnCol) {
			return _sqlite3MisuseError(tls, int32(96077))
		} else {
			iStore = int32(_sqlite3TableColumnToStorage(tls, (*TPreUpdate)(unsafe.Pointer(p)).FpTab, int16(iIdx)))
		}
	}
	if iStore >= int32((*TVdbeCursor)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).FpCsr)).FnField) || iStore < 0 {
		rc = int32(SQLITE_RANGE)
		goto preupdate_new_out
	}
	if (*TPreUpdate)(unsafe.Pointer(p)).Fop == int32(SQLITE_INSERT) {
		/* For an INSERT, memory cell p->iNewReg contains the serialized record
		 ** that is being inserted. Deserialize it. */
		pUnpack = (*TPreUpdate)(unsafe.Pointer(p)).FpNewUnpacked
		if !(pUnpack != 0) {
			pData = (*TVdbe)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).Fv)).FaMem + uintptr((*TPreUpdate)(unsafe.Pointer(p)).FiNewReg)*40
			if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pData)).Fflags)&int32(MEM_Zero) != 0 {
				v1 = _sqlite3VdbeMemExpandBlob(tls, pData)
			} else {
				v1 = 0
			}
			rc = v1
			if rc != SQLITE_OK {
				goto preupdate_new_out
			}
			pUnpack = _vdbeUnpackRecord(tls, (*TPreUpdate)(unsafe.Pointer(p)).FpKeyinfo, (*TMem)(unsafe.Pointer(pData)).Fn, (*TMem)(unsafe.Pointer(pData)).Fz)
			if !(pUnpack != 0) {
				rc = int32(SQLITE_NOMEM)
				goto preupdate_new_out
			}
			(*TPreUpdate)(unsafe.Pointer(p)).FpNewUnpacked = pUnpack
		}
		pMem = (*TUnpackedRecord)(unsafe.Pointer(pUnpack)).FaMem + uintptr(iStore)*40
		if iIdx == int32((*TTable)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).FpTab)).FiPKey) {
			_sqlite3VdbeMemSetInt64(tls, pMem, (*TPreUpdate)(unsafe.Pointer(p)).FiKey2)
		} else {
			if iStore >= libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(pUnpack)).FnField) {
				pMem = _columnNullValue(tls)
			}
		}
	} else {
		/* For an UPDATE, memory cell (p->iNewReg+1+iStore) contains the required
		 ** value. Make a copy of the cell contents and return a pointer to it.
		 ** It is not safe to return a pointer to the memory cell itself as the
		 ** caller may modify the value text encoding.
		 */
		if !((*TPreUpdate)(unsafe.Pointer(p)).FaNew != 0) {
			(*TPreUpdate)(unsafe.Pointer(p)).FaNew = _sqlite3DbMallocZero(tls, db, uint64(uint32(40)*libc.Uint32FromInt16((*TVdbeCursor)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).FpCsr)).FnField)))
			if !((*TPreUpdate)(unsafe.Pointer(p)).FaNew != 0) {
				rc = int32(SQLITE_NOMEM)
				goto preupdate_new_out
			}
		}
		pMem = (*TPreUpdate)(unsafe.Pointer(p)).FaNew + uintptr(iStore)*40
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags) == 0 {
			if iIdx == int32((*TTable)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).FpTab)).FiPKey) {
				_sqlite3VdbeMemSetInt64(tls, pMem, (*TPreUpdate)(unsafe.Pointer(p)).FiKey2)
			} else {
				rc = _sqlite3VdbeMemCopy(tls, pMem, (*TVdbe)(unsafe.Pointer((*TPreUpdate)(unsafe.Pointer(p)).Fv)).FaMem+uintptr((*TPreUpdate)(unsafe.Pointer(p)).FiNewReg+int32(1)+iStore)*40)
				if rc != SQLITE_OK {
					goto preupdate_new_out
				}
			}
		}
	}
	**(**uintptr)(__ccgo_up(ppValue)) = pMem
	goto preupdate_new_out
preupdate_new_out:
	;
	_sqlite3Error(tls, db, rc)
	return _sqlite3ApiExit(tls, db, rc)
}

/************** End of vdbeapi.c *********************************************/
/************** Begin file vdbetrace.c ***************************************/
/*
** 2009 November 25
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to insert the values of host parameters
** (aka "wildcards") into the SQL text output by sqlite3_trace().
**
** The Vdbe parse-tree explainer is also found here.
 */
/* #include "sqliteInt.h" */
/* #include "vdbeInt.h" */

// C documentation
//
//	/*
//	** Return N random bytes.
//	*/
func Xsqlite3_randomness(tls *libc.TLS, N int32, pBuf uintptr) {
	var mutex, pVfs, zBuf, v1 uintptr
	_, _, _, _ = mutex, pVfs, zBuf, v1
	zBuf = pBuf
	if Xsqlite3_initialize(tls) != 0 {
		return
	}
	mutex = _sqlite3MutexAlloc(tls, int32(SQLITE_MUTEX_STATIC_PRNG))
	Xsqlite3_mutex_enter(tls, mutex)
	if N <= 0 || pBuf == uintptr(0) {
		**(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)))) = uint32(0)
		Xsqlite3_mutex_leave(tls, mutex)
		return
	}
	/* Initialize the state of the random number generator once,
	 ** the first time this routine is called.
	 */
	if **(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)))) == uint32(0) {
		pVfs = Xsqlite3_vfs_find(tls, uintptr(0))
		libc.Xmemcpy(tls, uintptr(unsafe.Pointer(&_sqlite3Prng)), uintptr(unsafe.Pointer(&_chacha20_init)), uint32(16))
		if pVfs == uintptr(0) {
			libc.Xmemset(tls, uintptr(unsafe.Pointer(&_sqlite3Prng))+4*4, 0, uint32(44))
		} else {
			_sqlite3OsRandomness(tls, pVfs, int32(44), uintptr(unsafe.Pointer(&_sqlite3Prng))+4*4)
		}
		**(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)) + 15*4)) = **(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)) + 12*4))
		**(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)) + 12*4)) = uint32(0)
		_sqlite3Prng.Fn = uint8(0)
	}
	for int32(1) != 0 {
		if N <= libc.Int32FromUint8(_sqlite3Prng.Fn) {
			libc.Xmemcpy(tls, zBuf, uintptr(unsafe.Pointer(&_sqlite3Prng))+64+uintptr(libc.Int32FromUint8(_sqlite3Prng.Fn)-N), libc.Uint32FromInt32(N))
			v1 = uintptr(unsafe.Pointer(&_sqlite3Prng)) + 128
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) - N)
			break
		}
		if libc.Int32FromUint8(_sqlite3Prng.Fn) > 0 {
			libc.Xmemcpy(tls, zBuf, uintptr(unsafe.Pointer(&_sqlite3Prng))+64, uint32(_sqlite3Prng.Fn))
			N = N - libc.Int32FromUint8(_sqlite3Prng.Fn)
			zBuf = zBuf + uintptr(_sqlite3Prng.Fn)
		}
		**(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)) + 12*4)) = **(**Tu32)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Prng)) + 12*4)) + 1
		_chacha_block(tls, uintptr(unsafe.Pointer(&_sqlite3Prng))+64, uintptr(unsafe.Pointer(&_sqlite3Prng)))
		_sqlite3Prng.Fn = uint8(64)
	}
	Xsqlite3_mutex_leave(tls, mutex)
}

// C documentation
//
//	/*
//	** Obtain a snapshot handle for the snapshot of database zDb currently
//	** being read by handle db.
//	*/
func Xsqlite3_snapshot_get(tls *libc.TLS, db uintptr, zDb uintptr, ppSnapshot uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iDb, rc int32
	var pBt, pPager uintptr
	var _ /* dummy at bp+0 */ Ti64
	_, _, _, _ = iDb, pBt, pPager, rc
	rc = int32(SQLITE_ERROR)
	Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FautoCommit) == 0 {
		iDb = _sqlite3FindDbName(tls, db, zDb)
		if iDb == 0 || iDb > int32(1) {
			pBt = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpBt
			if int32(SQLITE_TXN_WRITE) != _sqlite3BtreeTxnState(tls, pBt) {
				pPager = _sqlite3BtreePager(tls, pBt)
				**(**Ti64)(__ccgo_up(bp)) = 0
				_sqlite3PagerSnapshotOpen(tls, pPager, bp)
				rc = _sqlite3BtreeBeginTrans(tls, pBt, 0, uintptr(0))
				_sqlite3PagerSnapshotOpen(tls, pPager, uintptr(0))
				if rc == SQLITE_OK {
					rc = _sqlite3PagerSnapshotGet(tls, _sqlite3BtreePager(tls, pBt), ppSnapshot)
				}
			}
		}
	}
	Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	return rc
}

// C documentation
//
//	/*
//	** Open a read-transaction on the snapshot identified by pSnapshot.
//	*/
func Xsqlite3_snapshot_open(tls *libc.TLS, db uintptr, zDb uintptr, pSnapshot uintptr) (r int32) {
	var bUnlock, iDb, rc int32
	var pBt, pPager uintptr
	_, _, _, _, _ = bUnlock, iDb, pBt, pPager, rc
	rc = int32(SQLITE_ERROR)
	Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FautoCommit) == 0 {
		iDb = _sqlite3FindDbName(tls, db, zDb)
		if iDb == 0 || iDb > int32(1) {
			pBt = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpBt
			if _sqlite3BtreeTxnState(tls, pBt) != int32(SQLITE_TXN_WRITE) {
				pPager = _sqlite3BtreePager(tls, pBt)
				bUnlock = 0
				if _sqlite3BtreeTxnState(tls, pBt) != SQLITE_TXN_NONE {
					if (*Tsqlite3)(unsafe.Pointer(db)).FnVdbeActive == 0 {
						rc = _sqlite3PagerSnapshotCheck(tls, pPager, pSnapshot)
						if rc == SQLITE_OK {
							bUnlock = int32(1)
							rc = _sqlite3BtreeCommit(tls, pBt)
						}
					}
				} else {
					rc = SQLITE_OK
				}
				if rc == SQLITE_OK {
					rc = _sqlite3PagerSnapshotOpen(tls, pPager, pSnapshot)
				}
				if rc == SQLITE_OK {
					rc = _sqlite3BtreeBeginTrans(tls, pBt, 0, uintptr(0))
					_sqlite3PagerSnapshotOpen(tls, pPager, uintptr(0))
				}
				if bUnlock != 0 {
					_sqlite3PagerSnapshotUnlock(tls, pPager)
				}
			}
		}
	}
	Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	return rc
}

// C documentation
//
//	/*
//	** Query status information.
//	*/
func Xsqlite3_status64(tls *libc.TLS, op int32, pCurrent uintptr, pHighwater uintptr, resetFlag int32) (r int32) {
	var pMutex, v1 uintptr
	_, _ = pMutex, v1
	if op < 0 || op >= libc.Int32FromUint32(libc.Uint32FromInt64(40)/libc.Uint32FromInt64(4)) {
		return _sqlite3MisuseError(tls, int32(25154))
	}
	if _statMutex[op] != 0 {
		v1 = _sqlite3Pcache1Mutex(tls)
	} else {
		v1 = _sqlite3MallocMutex(tls)
	}
	pMutex = v1
	Xsqlite3_mutex_enter(tls, pMutex)
	**(**Tsqlite3_int64)(__ccgo_up(pCurrent)) = libc.Int64FromUint32(**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4)))
	**(**Tsqlite3_int64)(__ccgo_up(pHighwater)) = libc.Int64FromUint32(**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)))
	if resetFlag != 0 {
		**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)) = **(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4))
	}
	Xsqlite3_mutex_leave(tls, pMutex)
	_ = pMutex /* Prevent warning when SQLITE_THREADSAFE=0 */
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Append N bytes of text from z to the StrAccum object.  Increase the
//	** size of the memory allocation for StrAccum if necessary.
//	*/
func Xsqlite3_str_append(tls *libc.TLS, p uintptr, z uintptr, N int32) {
	if (*Tsqlite3_str)(unsafe.Pointer(p)).FnChar+libc.Uint32FromInt32(N) >= (*Tsqlite3_str)(unsafe.Pointer(p)).FnAlloc {
		_enlargeAndAppend(tls, p, z, N)
	} else {
		if N != 0 {
			**(**Tu32)(__ccgo_up(p + 16)) += libc.Uint32FromInt32(N)
			libc.Xmemcpy(tls, (*Tsqlite3_str)(unsafe.Pointer(p)).FzText+uintptr((*Tsqlite3_str)(unsafe.Pointer(p)).FnChar-libc.Uint32FromInt32(N)), z, libc.Uint32FromInt32(N))
		}
	}
}

// C documentation
//
//	/*
//	** Reset an StrAccum string.  Reclaim all malloced memory.
//	*/
func Xsqlite3_str_reset(tls *libc.TLS, p uintptr) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint8((*TStrAccum)(unsafe.Pointer(p)).FprintfFlags)&int32(SQLITE_PRINTF_MALLOCED) != 0 {
		_sqlite3DbFree(tls, (*TStrAccum)(unsafe.Pointer(p)).Fdb, (*TStrAccum)(unsafe.Pointer(p)).FzText)
		v1 = p + 21
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(SQLITE_PRINTF_MALLOCED))
	}
	(*TStrAccum)(unsafe.Pointer(p)).FnAlloc = uint32(0)
	(*TStrAccum)(unsafe.Pointer(p)).FnChar = uint32(0)
	(*TStrAccum)(unsafe.Pointer(p)).FzText = uintptr(0)
}

// C documentation
//
//	/**************************** sqlite3_value_  *******************************
//	** The following routines extract information from a Mem or sqlite3_value
//	** structure.
//	*/
func Xsqlite3_value_blob(tls *libc.TLS, pVal uintptr) (r uintptr) {
	var p, v2 uintptr
	var v1 int32
	_, _, _ = p, v1, v2
	p = pVal
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_Blob)|libc.Int32FromInt32(MEM_Str)) != 0 {
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&int32(MEM_Zero) != 0 {
			v1 = _sqlite3VdbeMemExpandBlob(tls, p)
		} else {
			v1 = 0
		}
		if v1 != SQLITE_OK {
			return uintptr(0)
		}
		v2 = p + 16
		*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(MEM_Blob))
		if (*TMem)(unsafe.Pointer(p)).Fn != 0 {
			v2 = (*TMem)(unsafe.Pointer(p)).Fz
		} else {
			v2 = uintptr(0)
		}
		return v2
	} else {
		return Xsqlite3_value_text(tls, pVal)
	}
	return r
}

// C documentation
//
//	/* Make a copy of an sqlite3_value object
//	*/
func Xsqlite3_value_dup(tls *libc.TLS, pOrig uintptr) (r uintptr) {
	var pNew, v1 uintptr
	_, _ = pNew, v1
	if pOrig == uintptr(0) {
		return uintptr(0)
	}
	pNew = Xsqlite3_malloc(tls, int32(40))
	if pNew == uintptr(0) {
		return uintptr(0)
	}
	libc.Xmemset(tls, pNew, 0, uint32(40))
	libc.Xmemcpy(tls, pNew, pOrig, uint32(libc.UintptrFromInt32(0)+20))
	v1 = pNew + 16
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(MEM_Dyn))
	(*Tsqlite3_value)(unsafe.Pointer(pNew)).Fdb = uintptr(0)
	if libc.Int32FromUint16((*Tsqlite3_value)(unsafe.Pointer(pNew)).Fflags)&(libc.Int32FromInt32(MEM_Str)|libc.Int32FromInt32(MEM_Blob)) != 0 {
		v1 = pNew + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Static) | libc.Int32FromInt32(MEM_Dyn)))
		v1 = pNew + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_Ephem))
		if _sqlite3VdbeMemMakeWriteable(tls, pNew) != SQLITE_OK {
			_sqlite3ValueFree(tls, pNew)
			pNew = uintptr(0)
		}
	} else {
		if libc.Int32FromUint16((*Tsqlite3_value)(unsafe.Pointer(pNew)).Fflags)&int32(MEM_Null) != 0 {
			/* Do not duplicate pointer values */
			v1 = pNew + 16
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Term) | libc.Int32FromInt32(MEM_Subtype)))
		}
	}
	return pNew
}

func Xsqlite3_value_pointer(tls *libc.TLS, pVal uintptr, zPType uintptr) (r uintptr) {
	var p uintptr
	_ = p
	p = pVal
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Term)|libc.Int32FromInt32(MEM_Subtype)) == libc.Int32FromInt32(MEM_Null)|libc.Int32FromInt32(MEM_Term)|libc.Int32FromInt32(MEM_Subtype) && zPType != uintptr(0) && libc.Int32FromUint8((*TMem)(unsafe.Pointer(p)).FeSubtype) == int32('p') && libc.Xstrcmp(tls, *(*uintptr)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(p)).Fu)), zPType) == 0 {
		return (*TMem)(unsafe.Pointer(p)).Fz
	} else {
		return uintptr(0)
	}
	return r
}

// C documentation
//
//	/*
//	** Configure the change currently under construction with a blob value.
//	*/
func Xsqlite3changegroup_change_blob(tls *libc.TLS, pGrp uintptr, bNew int32, iCol int32, pVal uintptr, nVal int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nByte Tsqlite3_int64
	var rc, v1 int32
	var _ /* pBuf at bp+0 */ uintptr
	_, _, _ = nByte, rc, v1
	nByte = int64(int32(1)+_sessionVarintLen(tls, nVal)) + int64(nVal)
	rc = SQLITE_OK
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	v1 = _checkChangeParams(tls, pGrp, bNew, iCol, nByte, bp)
	rc = v1
	if SQLITE_OK != v1 {
		return rc
	}
	**(**Tu8)(__ccgo_up((*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf)) = uint8(SQLITE_BLOB)
	(*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnBuf = int32(1) + _sessionVarintPut(tls, (*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf+1, nVal)
	libc.Xmemcpy(tls, (*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnBuf), pVal, libc.Uint32FromInt32(nVal))
	**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(bp)) + 4)) += nVal
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Configure the change currently under construction with a text value.
//	*/
func Xsqlite3changegroup_change_text(tls *libc.TLS, pGrp uintptr, bNew int32, iCol int32, pVal uintptr, nVal int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nByte Tsqlite3_int64
	var nText, rc, v2 int32
	var v1 uint32
	var _ /* pBuf at bp+0 */ uintptr
	_, _, _, _, _ = nByte, nText, rc, v1, v2
	if nVal >= 0 {
		v1 = libc.Uint32FromInt32(nVal)
	} else {
		v1 = libc.Xstrlen(tls, pVal)
	}
	nText = libc.Int32FromUint32(v1)
	nByte = int64(int32(1) + _sessionVarintLen(tls, nText) + nText)
	rc = SQLITE_OK
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	v2 = _checkChangeParams(tls, pGrp, bNew, iCol, nByte, bp)
	rc = v2
	if SQLITE_OK != v2 {
		return rc
	}
	**(**Tu8)(__ccgo_up((*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf)) = uint8(SQLITE_TEXT)
	(*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnBuf = int32(1) + _sessionVarintPut(tls, (*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf+1, nText)
	libc.Xmemcpy(tls, (*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnBuf), pVal, libc.Uint32FromInt32(nText))
	**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(bp)) + 4)) += nText
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Create an RBU VFS named zName that accesses the underlying file-system
//	** via existing VFS zParent. The new object is registered as a non-default
//	** VFS with SQLite before returning.
//	*/
func Xsqlite3rbu_create_vfs(tls *libc.TLS, zName uintptr, zParent uintptr) (r int32) {
	var nByte, nName Tsize_t
	var pNew, pParent, zSpace, v1 uintptr
	var rc int32
	_, _, _, _, _, _, _ = nByte, nName, pNew, pParent, rc, zSpace, v1
	pNew = uintptr(0) /* Newly allocated VFS */
	rc = SQLITE_OK
	nName = libc.Xstrlen(tls, zName)
	nByte = uint32(108) + nName + uint32(1)
	pNew = Xsqlite3_malloc64(tls, uint64(nByte))
	if pNew == uintptr(0) {
		rc = int32(SQLITE_NOMEM)
	} else { /* Parent VFS */
		libc.Xmemset(tls, pNew, 0, nByte)
		pParent = Xsqlite3_vfs_find(tls, zParent)
		if pParent == uintptr(0) {
			rc = int32(SQLITE_NOTFOUND)
		} else {
			libc.Xmemcpy(tls, pNew, uintptr(unsafe.Pointer(&_vfs_template)), uint32(88))
			(*Trbu_vfs)(unsafe.Pointer(pNew)).Fbase.FmxPathname = (*Tsqlite3_vfs)(unsafe.Pointer(pParent)).FmxPathname
			(*Trbu_vfs)(unsafe.Pointer(pNew)).Fbase.FszOsFile = libc.Int32FromUint32(uint32(64) + libc.Uint32FromInt32((*Tsqlite3_vfs)(unsafe.Pointer(pParent)).FszOsFile))
			(*Trbu_vfs)(unsafe.Pointer(pNew)).FpRealVfs = pParent
			v1 = pNew + 1*108
			zSpace = v1
			(*Trbu_vfs)(unsafe.Pointer(pNew)).Fbase.FzName = v1
			libc.Xmemcpy(tls, zSpace, zName, nName)
			/* Allocate the mutex and register the new VFS (not as the default) */
			(*Trbu_vfs)(unsafe.Pointer(pNew)).Fmutex = Xsqlite3_mutex_alloc(tls, int32(SQLITE_MUTEX_RECURSIVE))
			if (*Trbu_vfs)(unsafe.Pointer(pNew)).Fmutex == uintptr(0) {
				rc = int32(SQLITE_NOMEM)
			} else {
				rc = Xsqlite3_vfs_register(tls, pNew, 0)
			}
		}
		if rc != SQLITE_OK {
			Xsqlite3_mutex_free(tls, (*Trbu_vfs)(unsafe.Pointer(pNew)).Fmutex)
			Xsqlite3_free(tls, pNew)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Attach a table to a session. All subsequent changes made to the table
//	** while the session object is enabled will be recorded.
//	**
//	** Only tables that have a PRIMARY KEY defined may be attached. It does
//	** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
//	** or not.
//	*/
func Xsqlite3session_attach(tls *libc.TLS, pSession uintptr, zName uintptr) (r int32) {
	var nByte, nName, rc int32
	var pTab, ppTab uintptr
	_, _, _, _, _ = nByte, nName, pTab, ppTab, rc
	rc = SQLITE_OK
	Xsqlite3_mutex_enter(tls, Xsqlite3_db_mutex(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fdb))
	if !(zName != 0) {
		(*Tsqlite3_session)(unsafe.Pointer(pSession)).FbAutoAttach = int32(1)
	} else { /* Number of bytes in string zName */
		/* First search for an existing entry. If one is found, this call is
		 ** a no-op. Return early. */
		nName = _sqlite3Strlen30(tls, zName)
		pTab = (*Tsqlite3_session)(unsafe.Pointer(pSession)).FpTable
		for {
			if !(pTab != 0) {
				break
			}
			if 0 == Xsqlite3_strnicmp(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, zName, nName+int32(1)) {
				break
			}
			goto _1
		_1:
			;
			pTab = (*TSessionTable)(unsafe.Pointer(pTab)).FpNext
		}
		if !(pTab != 0) {
			/* Allocate new SessionTable object. */
			nByte = libc.Int32FromUint32(uint32(56) + libc.Uint32FromInt32(nName) + uint32(1))
			pTab = _sessionMalloc64(tls, pSession, int64(nByte))
			if !(pTab != 0) {
				rc = int32(SQLITE_NOMEM)
			} else {
				libc.Xmemset(tls, pTab, 0, uint32(56))
				(*TSessionTable)(unsafe.Pointer(pTab)).FzName = pTab + 1*56
				libc.Xmemcpy(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, zName, libc.Uint32FromInt32(nName+int32(1)))
				ppTab = pSession + 64
				for {
					if !(**(**uintptr)(__ccgo_up(ppTab)) != 0) {
						break
					}
					goto _2
				_2:
					;
					ppTab = **(**uintptr)(__ccgo_up(ppTab))
				}
				**(**uintptr)(__ccgo_up(ppTab)) = pTab
			}
		}
	}
	Xsqlite3_mutex_leave(tls, Xsqlite3_db_mutex(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fdb))
	return rc
}

// C documentation
//
//	/*
//	** Create a session object. This session object will record changes to
//	** database zDb attached to connection db.
//	*/
func Xsqlite3session_create(tls *libc.TLS, db uintptr, zDb uintptr, ppSession uintptr) (r int32) {
	var nDb int32
	var pNew, pOld uintptr
	_, _, _ = nDb, pNew, pOld        /* Session object already attached to db */
	nDb = _sqlite3Strlen30(tls, zDb) /* Length of zDb in bytes */
	/* Zero the output value in case an error occurs. */
	**(**uintptr)(__ccgo_up(ppSession)) = uintptr(0)
	/* Allocate and populate the new session object. */
	pNew = Xsqlite3_malloc64(tls, uint64(uint32(88)+libc.Uint32FromInt32(nDb)+uint32(1)))
	if !(pNew != 0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, pNew, 0, uint32(88))
	(*Tsqlite3_session)(unsafe.Pointer(pNew)).Fdb = db
	(*Tsqlite3_session)(unsafe.Pointer(pNew)).FzDb = pNew + 1*88
	(*Tsqlite3_session)(unsafe.Pointer(pNew)).FbEnable = int32(1)
	libc.Xmemcpy(tls, (*Tsqlite3_session)(unsafe.Pointer(pNew)).FzDb, zDb, libc.Uint32FromInt32(nDb+int32(1)))
	_sessionPreupdateHooks(tls, pNew)
	/* Add the new session object to the linked list of session objects
	 ** attached to database handle $db. Do this under the cover of the db
	 ** handle mutex.  */
	Xsqlite3_mutex_enter(tls, Xsqlite3_db_mutex(tls, db))
	pOld = Xsqlite3_preupdate_hook(tls, db, __ccgo_fp(_xPreUpdate), pNew)
	(*Tsqlite3_session)(unsafe.Pointer(pNew)).FpNext = pOld
	Xsqlite3_mutex_leave(tls, Xsqlite3_db_mutex(tls, db))
	**(**uintptr)(__ccgo_up(ppSession)) = pNew
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Arguments aIdx, aCell and aSpare all point to arrays of size
//	** nIdx. The aIdx array contains the set of integers from 0 to
//	** (nIdx-1) in no particular order. This function sorts the values
//	** in aIdx according to dimension iDim of the cells in aCell. The
//	** minimum value of dimension iDim is considered first, the
//	** maximum used to break ties.
//	**
//	** The aSpare array is used as temporary working space by the
//	** sorting algorithm.
//	*/
func _SortByDimension(tls *libc.TLS, pRtree uintptr, aIdx uintptr, nIdx int32, iDim int32, aCell uintptr, aSpare uintptr) {
	var aLeft, aRight uintptr
	var iLeft, iRight, nLeft, nRight int32
	var xleft1, xleft2, xright1, xright2 TRtreeDValue
	var v1, v2, v3, v4 float64
	_, _, _, _, _, _, _, _, _, _, _, _, _, _ = aLeft, aRight, iLeft, iRight, nLeft, nRight, xleft1, xleft2, xright1, xright2, v1, v2, v3, v4
	if nIdx > int32(1) {
		iLeft = 0
		iRight = 0
		nLeft = nIdx / int32(2)
		nRight = nIdx - nLeft
		aLeft = aIdx
		aRight = aIdx + uintptr(nLeft)*4
		_SortByDimension(tls, pRtree, aLeft, nLeft, iDim, aCell, aSpare)
		_SortByDimension(tls, pRtree, aRight, nRight, iDim, aCell, aSpare)
		libc.Xmemcpy(tls, aSpare, aLeft, uint32(4)*libc.Uint32FromInt32(nLeft))
		aLeft = aSpare
		for iLeft < nLeft || iRight < nRight {
			if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
				v1 = float64(*(*TRtreeValue)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aLeft + uintptr(iLeft)*4)))*48 + 8 + uintptr(iDim*int32(2))*4)))
			} else {
				v1 = float64(*(*int32)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aLeft + uintptr(iLeft)*4)))*48 + 8 + uintptr(iDim*int32(2))*4)))
			}
			xleft1 = v1
			if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
				v2 = float64(*(*TRtreeValue)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aLeft + uintptr(iLeft)*4)))*48 + 8 + uintptr(iDim*int32(2)+int32(1))*4)))
			} else {
				v2 = float64(*(*int32)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aLeft + uintptr(iLeft)*4)))*48 + 8 + uintptr(iDim*int32(2)+int32(1))*4)))
			}
			xleft2 = v2
			if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
				v3 = float64(*(*TRtreeValue)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aRight + uintptr(iRight)*4)))*48 + 8 + uintptr(iDim*int32(2))*4)))
			} else {
				v3 = float64(*(*int32)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aRight + uintptr(iRight)*4)))*48 + 8 + uintptr(iDim*int32(2))*4)))
			}
			xright1 = v3
			if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
				v4 = float64(*(*TRtreeValue)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aRight + uintptr(iRight)*4)))*48 + 8 + uintptr(iDim*int32(2)+int32(1))*4)))
			} else {
				v4 = float64(*(*int32)(unsafe.Pointer(aCell + uintptr(**(**int32)(__ccgo_up(aRight + uintptr(iRight)*4)))*48 + 8 + uintptr(iDim*int32(2)+int32(1))*4)))
			}
			xright2 = v4
			if iLeft != nLeft && (iRight == nRight || xleft1 < xright1 || xleft1 == xright1 && xleft2 < xright2) {
				**(**int32)(__ccgo_up(aIdx + uintptr(iLeft+iRight)*4)) = **(**int32)(__ccgo_up(aLeft + uintptr(iLeft)*4))
				iLeft = iLeft + 1
			} else {
				**(**int32)(__ccgo_up(aIdx + uintptr(iLeft+iRight)*4)) = **(**int32)(__ccgo_up(aRight + uintptr(iRight)*4))
				iRight = iRight + 1
			}
		}
	}
}

func _SplitNode(tls *libc.TLS, pRtree uintptr, pNode uintptr, pCell uintptr, iHeight int32) (r int32) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var aCell, aiUsed, pLeft, pParent, pRight uintptr
	var i, nCell, newCellIsRight, rc, v2, v3 int32
	var iRowid, iRowid1 Ti64
	var v4, v5 bool
	var _ /* iCell at bp+96 */ int32
	var _ /* leftbbox at bp+0 */ TRtreeCell
	var _ /* rightbbox at bp+48 */ TRtreeCell
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aCell, aiUsed, i, iRowid, iRowid1, nCell, newCellIsRight, pLeft, pParent, pRight, rc, v2, v3, v4, v5
	newCellIsRight = 0
	rc = SQLITE_OK
	nCell = _readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData+2)
	pLeft = uintptr(0)
	pRight = uintptr(0)
	/* Allocate an array and populate it with a copy of pCell and
	 ** all cells from node pLeft. Then zero the original node.
	 */
	aCell = Xsqlite3_malloc64(tls, uint64((libc.Uint32FromInt64(48)+libc.Uint32FromInt64(4))*libc.Uint32FromInt32(nCell+libc.Int32FromInt32(1))))
	if !(aCell != 0) {
		rc = int32(SQLITE_NOMEM)
		goto splitnode_out
	}
	aiUsed = aCell + uintptr(nCell+int32(1))*48
	libc.Xmemset(tls, aiUsed, 0, uint32(4)*libc.Uint32FromInt32(nCell+libc.Int32FromInt32(1)))
	i = 0
	for {
		if !(i < nCell) {
			break
		}
		_nodeGetCell(tls, pRtree, pNode, i, aCell+uintptr(i)*48)
		goto _1
	_1:
		;
		i = i + 1
	}
	_nodeZero(tls, pRtree, pNode)
	libc.Xmemcpy(tls, aCell+uintptr(nCell)*48, pCell, uint32(48))
	nCell = nCell + 1
	if (*TRtreeNode)(unsafe.Pointer(pNode)).FiNode == int64(1) {
		pRight = _nodeNew(tls, pRtree, pNode)
		pLeft = _nodeNew(tls, pRtree, pNode)
		(*TRtree)(unsafe.Pointer(pRtree)).FiDepth = (*TRtree)(unsafe.Pointer(pRtree)).FiDepth + 1
		(*TRtreeNode)(unsafe.Pointer(pNode)).FisDirty = int32(1)
		_writeInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData, (*TRtree)(unsafe.Pointer(pRtree)).FiDepth)
	} else {
		pLeft = pNode
		pRight = _nodeNew(tls, pRtree, (*TRtreeNode)(unsafe.Pointer(pLeft)).FpParent)
		(*TRtreeNode)(unsafe.Pointer(pLeft)).FnRef = (*TRtreeNode)(unsafe.Pointer(pLeft)).FnRef + 1
	}
	if !(pLeft != 0) || !(pRight != 0) {
		rc = int32(SQLITE_NOMEM)
		goto splitnode_out
	}
	libc.Xmemset(tls, (*TRtreeNode)(unsafe.Pointer(pLeft)).FzData, 0, libc.Uint32FromInt32((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize))
	libc.Xmemset(tls, (*TRtreeNode)(unsafe.Pointer(pRight)).FzData, 0, libc.Uint32FromInt32((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize))
	rc = _splitNodeStartree(tls, pRtree, aCell, nCell, pLeft, pRight, bp, bp+48)
	if rc != SQLITE_OK {
		goto splitnode_out
	}
	/* Ensure both child nodes have node numbers assigned to them by calling
	 ** nodeWrite(). Node pRight always needs a node number, as it was created
	 ** by nodeNew() above. But node pLeft sometimes already has a node number.
	 ** In this case avoid the all to nodeWrite().
	 */
	v2 = _nodeWrite(tls, pRtree, pRight)
	rc = v2
	if v5 = SQLITE_OK != v2; !v5 {
		if v4 = 0 == (*TRtreeNode)(unsafe.Pointer(pLeft)).FiNode; v4 {
			v3 = _nodeWrite(tls, pRtree, pLeft)
			rc = v3
		}
	}
	if v5 || v4 && SQLITE_OK != v3 {
		goto splitnode_out
	}
	(**(**TRtreeCell)(__ccgo_up(bp + 48))).FiRowid = (*TRtreeNode)(unsafe.Pointer(pRight)).FiNode
	(**(**TRtreeCell)(__ccgo_up(bp))).FiRowid = (*TRtreeNode)(unsafe.Pointer(pLeft)).FiNode
	if (*TRtreeNode)(unsafe.Pointer(pNode)).FiNode == int64(1) {
		rc = _rtreeInsertCell(tls, pRtree, (*TRtreeNode)(unsafe.Pointer(pLeft)).FpParent, bp, iHeight+int32(1))
		if rc != SQLITE_OK {
			goto splitnode_out
		}
	} else {
		pParent = (*TRtreeNode)(unsafe.Pointer(pLeft)).FpParent
		rc = _nodeParentIndex(tls, pRtree, pLeft, bp+96)
		if rc == SQLITE_OK {
			_nodeOverwriteCell(tls, pRtree, pParent, bp, **(**int32)(__ccgo_up(bp + 96)))
			rc = _AdjustTree(tls, pRtree, pParent, bp)
		}
		if rc != SQLITE_OK {
			goto splitnode_out
		}
	}
	v2 = _rtreeInsertCell(tls, pRtree, (*TRtreeNode)(unsafe.Pointer(pRight)).FpParent, bp+48, iHeight+int32(1))
	rc = v2
	if v2 != 0 {
		goto splitnode_out
	}
	i = 0
	for {
		if !(i < _readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pRight)).FzData+2)) {
			break
		}
		iRowid = _nodeGetRowid(tls, pRtree, pRight, i)
		rc = _updateMapping(tls, pRtree, iRowid, pRight, iHeight)
		if iRowid == (*TRtreeCell)(unsafe.Pointer(pCell)).FiRowid {
			newCellIsRight = int32(1)
		}
		if rc != SQLITE_OK {
			goto splitnode_out
		}
		goto _7
	_7:
		;
		i = i + 1
	}
	if (*TRtreeNode)(unsafe.Pointer(pNode)).FiNode == int64(1) {
		i = 0
		for {
			if !(i < _readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pLeft)).FzData+2)) {
				break
			}
			iRowid1 = _nodeGetRowid(tls, pRtree, pLeft, i)
			rc = _updateMapping(tls, pRtree, iRowid1, pLeft, iHeight)
			if rc != SQLITE_OK {
				goto splitnode_out
			}
			goto _8
		_8:
			;
			i = i + 1
		}
	} else {
		if newCellIsRight == 0 {
			rc = _updateMapping(tls, pRtree, (*TRtreeCell)(unsafe.Pointer(pCell)).FiRowid, pLeft, iHeight)
		}
	}
	goto splitnode_out
splitnode_out:
	;
	_nodeRelease(tls, pRtree, pRight)
	_nodeRelease(tls, pRtree, pLeft)
	Xsqlite3_free(tls, aCell)
	return rc
}

const __LONG_MAX = 2147483647

// C documentation
//
//	/*
//	** This function is used to read or overwrite payload information
//	** for the entry that the pCur cursor is pointing to. The eOp
//	** argument is interpreted as follows:
//	**
//	**   0: The operation is a read. Populate the overflow cache.
//	**   1: The operation is a write. Populate the overflow cache.
//	**
//	** A total of "amt" bytes are read or written beginning at "offset".
//	** Data is read to or from the buffer pBuf.
//	**
//	** The content being read or written might appear on the main page
//	** or be scattered out on multiple overflow pages.
//	**
//	** If the current cursor entry uses one or more overflow pages
//	** this function may allocate space for and lazily populate
//	** the overflow page-list cache array (BtCursor.aOverflow).
//	** Subsequent calls use this cache to make seeking to the supplied offset
//	** more efficient.
//	**
//	** Once an overflow page-list cache has been allocated, it must be
//	** invalidated if some other cursor writes to the same table, or if
//	** the cursor is moved to a different row. Additionally, in auto-vacuum
//	** mode, the following events may invalidate an overflow page-list cache.
//	**
//	**   * An incremental vacuum,
//	**   * A commit in auto_vacuum="full" mode,
//	**   * Creating a table (may require moving an overflow page).
//	*/
func _accessPayload(tls *libc.TLS, pCur uintptr, offset Tu32, amt Tu32, pBuf uintptr, eOp int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a, a1, iIdx, rc, v2 int32
	var aNew, aPayload, aWrite, fd, pBt, pBufStart, pPage, v1 uintptr
	var nOvfl Ti64
	var ovflSize Tu32
	var _ /* aSave at bp+4 */ [4]Tu8
	var _ /* nextPage at bp+0 */ TPgno
	var _ /* pDbPage at bp+8 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = a, a1, aNew, aPayload, aWrite, fd, iIdx, nOvfl, ovflSize, pBt, pBufStart, pPage, rc, v1, v2
	rc = SQLITE_OK
	iIdx = 0
	pPage = (*TBtCursor)(unsafe.Pointer(pCur)).FpPage /* Btree page of current entry */
	pBt = (*TBtCursor)(unsafe.Pointer(pCur)).FpBt     /* Btree this cursor belongs to */
	pBufStart = pBuf                                  /* Start of original out buffer */
	if libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Fix) >= libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) {
		return _sqlite3CorruptError(tls, int32(78371))
	}
	_getCellInfo(tls, pCur)
	aPayload = (*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload
	if libc.Uint32FromInt32(int32(aPayload)-int32((*TMemPage)(unsafe.Pointer(pPage)).FaData)) > (*TBtShared)(unsafe.Pointer(pBt)).FusableSize-uint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal) {
		/* Trying to read or write past the end of the data is an error.  The
		 ** conditional above is really:
		 **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
		 ** but is recast into its current form to avoid integer overflow problems
		 */
		return _sqlite3CorruptError(tls, int32(78386))
	}
	/* Check if data must be read/written to/from the btree page itself. */
	if offset < uint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal) {
		a = libc.Int32FromUint32(amt)
		if libc.Uint32FromInt32(a)+offset > uint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal) {
			a = libc.Int32FromUint32(uint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal) - offset)
		}
		rc = _copyPayload(tls, aPayload+uintptr(offset), pBuf, a, eOp, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
		offset = uint32(0)
		pBuf = pBuf + uintptr(a)
		amt = amt - libc.Uint32FromInt32(a)
	} else {
		offset = offset - uint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal)
	}
	if rc == SQLITE_OK && amt > uint32(0) {
		ovflSize = (*TBtShared)(unsafe.Pointer(pBt)).FusableSize - uint32(4)
		**(**TPgno)(__ccgo_up(bp)) = _sqlite3Get4byte(tls, aPayload+uintptr((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal))
		/* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
		 **
		 ** The aOverflow[] array is sized at one entry for each overflow page
		 ** in the overflow chain. The page number of the first overflow page is
		 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
		 ** means "not yet known" (the cache is lazily populated).
		 */
		if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FcurFlags)&int32(BTCF_ValidOvfl) == 0 {
			nOvfl = libc.Int64FromUint32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnPayload)
			nOvfl = (nOvfl - libc.Int64FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal) + libc.Int64FromUint32(ovflSize) - int64(1)) / libc.Int64FromUint32(ovflSize)
			if (*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow == uintptr(0) || nOvfl*int64(libc.Int32FromInt64(4)) > int64(_sqlite3MallocSize(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow)) {
				if _sqlite3FaultSim(tls, int32(413)) != 0 {
					aNew = uintptr(0)
				} else {
					aNew = _sqlite3Realloc(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow, libc.Uint64FromInt64(nOvfl*int64(2)*int64(4)))
				}
				if aNew == uintptr(0) {
					return int32(SQLITE_NOMEM)
				} else {
					(*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow = aNew
				}
			}
			libc.Xmemset(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow, 0, libc.Uint32FromInt64(nOvfl*int64(4)))
			v1 = pCur + 1
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTCF_ValidOvfl))
		} else {
			/* Sanity check the validity of the overflow page cache */
			/* If the overflow page-list cache has been allocated and the
			 ** entry for the first required overflow page is valid, skip
			 ** directly to it.
			 */
			if **(**TPgno)(__ccgo_up((*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow + uintptr(offset/ovflSize)*4)) != 0 {
				iIdx = libc.Int32FromUint32(offset / ovflSize)
				**(**TPgno)(__ccgo_up(bp)) = **(**TPgno)(__ccgo_up((*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow + uintptr(iIdx)*4))
				offset = offset % ovflSize
			}
		}
		for **(**TPgno)(__ccgo_up(bp)) != 0 {
			/* If required, populate the overflow page-list cache. */
			if **(**TPgno)(__ccgo_up(bp)) > (*TBtShared)(unsafe.Pointer(pBt)).FnPage {
				return _sqlite3CorruptError(tls, int32(78459))
			}
			**(**TPgno)(__ccgo_up((*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow + uintptr(iIdx)*4)) = **(**TPgno)(__ccgo_up(bp))
			if offset >= ovflSize {
				/* The only reason to read this page is to obtain the page
				 ** number for the next page in the overflow chain. The page
				 ** data is not required. So first try to lookup the overflow
				 ** page-list cache, if any, then fall back to the getOverflowPage()
				 ** function.
				 */
				if **(**TPgno)(__ccgo_up((*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow + uintptr(iIdx+int32(1))*4)) != 0 {
					**(**TPgno)(__ccgo_up(bp)) = **(**TPgno)(__ccgo_up((*TBtCursor)(unsafe.Pointer(pCur)).FaOverflow + uintptr(iIdx+int32(1))*4))
				} else {
					rc = _getOverflowPage(tls, pBt, **(**TPgno)(__ccgo_up(bp)), uintptr(0), bp)
				}
				offset = offset - ovflSize
			} else {
				/* Need to read this page properly. It contains some of the
				 ** range of data that is being read (eOp==0) or written (eOp!=0).
				 */
				a1 = libc.Int32FromUint32(amt)
				if libc.Uint32FromInt32(a1)+offset > ovflSize {
					a1 = libc.Int32FromUint32(ovflSize - offset)
				}
				/* If all the following are true:
				 **
				 **   1) this is a read operation, and
				 **   2) data is required from the start of this overflow page, and
				 **   3) there are no dirty pages in the page-cache
				 **   4) the database is file-backed, and
				 **   5) the page is not in the WAL file
				 **   6) at least 4 bytes have already been read into the output buffer
				 **
				 ** then data can be read directly from the database file into the
				 ** output buffer, bypassing the page-cache altogether. This speeds
				 ** up loading large records that span many overflow pages.
				 */
				if eOp == 0 && offset == uint32(0) && _sqlite3PagerDirectReadOk(tls, (*TBtShared)(unsafe.Pointer(pBt)).FpPager, **(**TPgno)(__ccgo_up(bp))) != 0 && pBuf+uintptr(-libc.Int32FromInt32(4)) >= pBufStart {
					fd = _sqlite3PagerFile(tls, (*TBtShared)(unsafe.Pointer(pBt)).FpPager)
					aWrite = pBuf + uintptr(-libc.Int32FromInt32(4))
					/* due to (6) */
					libc.Xmemcpy(tls, bp+4, aWrite, uint32(4))
					rc = _sqlite3OsRead(tls, fd, aWrite, a1+int32(4), libc.Int64FromUint32((*TBtShared)(unsafe.Pointer(pBt)).FpageSize)*libc.Int64FromUint32(**(**TPgno)(__ccgo_up(bp))-libc.Uint32FromInt32(1)))
					**(**TPgno)(__ccgo_up(bp)) = _sqlite3Get4byte(tls, aWrite)
					libc.Xmemcpy(tls, aWrite, bp+4, uint32(4))
				} else {
					if eOp == 0 {
						v2 = int32(PAGER_GET_READONLY)
					} else {
						v2 = 0
					}
					rc = _sqlite3PagerGet(tls, (*TBtShared)(unsafe.Pointer(pBt)).FpPager, **(**TPgno)(__ccgo_up(bp)), bp+8, v2)
					if rc == SQLITE_OK {
						if eOp != 0 && (_sqlite3PagerPageRefcount(tls, **(**uintptr)(__ccgo_up(bp + 8))) != int32(1) || (*TMemPage)(unsafe.Pointer(_sqlite3PagerGetExtra(tls, **(**uintptr)(__ccgo_up(bp + 8))))).FisInit != 0) {
							_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 8)))
							return _sqlite3CorruptError(tls, int32(78529))
						}
						aPayload = _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp + 8)))
						**(**TPgno)(__ccgo_up(bp)) = _sqlite3Get4byte(tls, aPayload)
						rc = _copyPayload(tls, aPayload+uintptr(offset+uint32(4)), pBuf, a1, eOp, **(**uintptr)(__ccgo_up(bp + 8)))
						_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 8)))
						offset = uint32(0)
					}
				}
				amt = amt - libc.Uint32FromInt32(a1)
				if amt == uint32(0) {
					return rc
				}
				pBuf = pBuf + uintptr(a1)
			}
			if rc != 0 {
				break
			}
			iIdx = iIdx + 1
		}
	}
	if rc == SQLITE_OK && amt > uint32(0) {
		/* Overflow chain ends prematurely */
		return _sqlite3CorruptError(tls, int32(78549))
	}
	return rc
}

func _addOp4IntSlow(tls *libc.TLS, p uintptr, op int32, p1 int32, p2 int32, p3 int32, p4 int32) (r int32) {
	var addr int32
	var pOp uintptr
	_, _ = addr, pOp
	addr = _sqlite3VdbeAddOp3(tls, p, op, p1, p2, p3)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).FmallocFailed) == 0 {
		pOp = (*TVdbe)(unsafe.Pointer(p)).FaOp + uintptr(addr)*20
		(*TVdbeOp)(unsafe.Pointer(pOp)).Fp4type = int8(-libc.Int32FromInt32(3))
		*(*int32)(unsafe.Pointer(pOp + 16)) = p4
	}
	return addr
}

// C documentation
//
//	/*
//	** The pOrderBy->a[].u.x.iOrderByCol values might be incorrect because
//	** columns might have been rearranged in the result set.  This routine
//	** fixes them up.
//	**
//	** pEList is the new result set.  The pEList->a[].u.x.iOrderByCol values
//	** contain the *old* locations of each expression.  This is a temporary
//	** use of u.x.iOrderByCol, not its intended use.  The caller must reset
//	** u.x.iOrderByCol back to zero for all entries in pEList before the
//	** caller returns.
//	**
//	** This routine changes pOrderBy->a[].u.x.iOrderByCol values from
//	** pEList->a[N].u.x.iOrderByCol into N+1.  (The "+1" is because of the 1-based
//	** indexing used by iOrderByCol.)  Or if no match, iOrderByCol is set to zero.
//	*/
func _adjustOrderByCol(tls *libc.TLS, pOrderBy uintptr, pEList uintptr) {
	var i, j, t int32
	_, _, _ = i, j, t
	if pOrderBy == uintptr(0) {
		return
	}
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr) {
			break
		}
		t = libc.Int32FromUint16(*(*Tu16)(unsafe.Pointer(pOrderBy + 8 + uintptr(i)*20 + 16)))
		if t == 0 {
			goto _1
		}
		j = 0
		for {
			if !(j < (*TExprList)(unsafe.Pointer(pEList)).FnExpr) {
				break
			}
			if libc.Int32FromUint16(*(*Tu16)(unsafe.Pointer(pEList + 8 + uintptr(j)*20 + 16))) == t {
				*(*Tu16)(unsafe.Pointer(pOrderBy + 8 + uintptr(i)*20 + 16)) = libc.Uint16FromInt32(j + int32(1))
				break
			}
			goto _2
		_2:
			;
			j = j + 1
		}
		if j >= (*TExprList)(unsafe.Pointer(pEList)).FnExpr {
			*(*Tu16)(unsafe.Pointer(pOrderBy + 8 + uintptr(i)*20 + 16)) = uint16(0)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
}

// C documentation
//
//	/*
//	** This is a Walker expression node callback.
//	**
//	** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
//	** object that is referenced does not refer directly to the Expr.  If
//	** it does, make a copy.  This is done because the pExpr argument is
//	** subject to change.
//	**
//	** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
//	** which builds on the sqlite3ParserAddCleanup() mechanism.
//	*/
func _agginfoPersistExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var db, pAggInfo, pParse uintptr
	var iAgg int32
	_, _, _, _ = db, iAgg, pAggInfo, pParse
	if !((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)|libc.Int32FromInt32(EP_Reduced)) != libc.Uint32FromInt32(0)) && (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo != uintptr(0) {
		pAggInfo = (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo
		iAgg = int32((*TExpr)(unsafe.Pointer(pExpr)).FiAgg)
		pParse = (*TWalker)(unsafe.Pointer(pWalker)).FpParse
		db = (*TParse)(unsafe.Pointer(pParse)).Fdb
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_AGG_FUNCTION) {
			if iAgg < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn && (**(**TAggInfo_col)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaCol + uintptr(iAgg)*20))).FpCExpr == pExpr {
				pExpr = _sqlite3ExprDup(tls, db, pExpr, 0)
				if pExpr != 0 && !(_sqlite3ExprDeferredDelete(tls, pParse, pExpr) != 0) {
					(**(**TAggInfo_col)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaCol + uintptr(iAgg)*20))).FpCExpr = pExpr
				}
			}
		} else {
			if iAgg < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnFunc && (**(**TAggInfo_func)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc + uintptr(iAgg)*24))).FpFExpr == pExpr {
				pExpr = _sqlite3ExprDup(tls, db, pExpr, 0)
				if pExpr != 0 && !(_sqlite3ExprDeferredDelete(tls, pParse, pExpr) != 0) {
					(**(**TAggInfo_func)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc + uintptr(iAgg)*24))).FpFExpr = pExpr
				}
			}
		}
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Walker callback for aggregateConvertIndexedExprRefToColumn().
//	*/
func _aggregateIdxEprRefToColCallback(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pAggInfo, pCol uintptr
	_, _ = pAggInfo, pCol
	_ = pWalker
	if (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo == uintptr(0) {
		return WRC_Continue
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_COLUMN) {
		return WRC_Continue
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_FUNCTION) {
		return WRC_Continue
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_IF_NULL_ROW) {
		return WRC_Continue
	}
	pAggInfo = (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo
	if int32((*TExpr)(unsafe.Pointer(pExpr)).FiAgg) >= (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn {
		return WRC_Continue
	}
	pCol = (*TAggInfo)(unsafe.Pointer(pAggInfo)).FaCol + uintptr((*TExpr)(unsafe.Pointer(pExpr)).FiAgg)*20
	(*TExpr)(unsafe.Pointer(pExpr)).Fop = uint8(TK_AGG_COLUMN)
	(*TExpr)(unsafe.Pointer(pExpr)).FiTable = (*TAggInfo_col)(unsafe.Pointer(pCol)).FiTable
	(*TExpr)(unsafe.Pointer(pExpr)).FiColumn = int16((*TAggInfo_col)(unsafe.Pointer(pCol)).FiColumn)
	**(**Tu32)(__ccgo_up(pExpr + 4)) &= ^libc.Uint32FromInt32(libc.Int32FromInt32(EP_Skip) | libc.Int32FromInt32(EP_Collate) | libc.Int32FromInt32(EP_Unlikely))
	return int32(WRC_Prune)
}

// C documentation
//
//	/*
//	** Allocate a new page from the database file.
//	**
//	** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
//	** has already been called on the new page.)  The new page has also
//	** been referenced and the calling routine is responsible for calling
//	** sqlite3PagerUnref() on the new page when it is done.
//	**
//	** SQLITE_OK is returned on success.  Any other return value indicates
//	** an error.  *ppPage is set to NULL in the event of an error.
//	**
//	** If the "nearby" parameter is not 0, then an effort is made to
//	** locate a page close to the page number "nearby".  This can be used in an
//	** attempt to keep related pages close to each other in the database file,
//	** which in turn can make database access faster.
//	**
//	** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
//	** anywhere on the free-list, then it is guaranteed to be returned.  If
//	** eMode is BTALLOC_LT then the page returned will be less than or equal
//	** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
//	** are no restrictions on which page is returned.
//	*/
func _allocateBtreePage(tls *libc.TLS, pBt uintptr, ppPage uintptr, pPgno uintptr, nearby TPgno, eMode Tu8) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aData, pPage1, pPrevTrunk uintptr
	var bNoContent, d2, dist, noContent, rc, v5 int32
	var closest, i, k, n, nSearch, v1 Tu32
	var iNewTrunk, iPage, iTrunk, mxPage TPgno
	var searchList Tu8
	var v2 bool
	var _ /* eType at bp+4 */ Tu8
	var _ /* pNewTrunk at bp+8 */ uintptr
	var _ /* pPg at bp+12 */ uintptr
	var _ /* pTrunk at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aData, bNoContent, closest, d2, dist, i, iNewTrunk, iPage, iTrunk, k, mxPage, n, nSearch, noContent, pPage1, pPrevTrunk, rc, searchList, v1, v2, v5 /* Number of leaves on the trunk of the freelist */
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	pPrevTrunk = uintptr(0) /* Total size of the database file */
	pPage1 = (*TBtShared)(unsafe.Pointer(pBt)).FpPage1
	mxPage = _btreePagecount(tls, pBt)
	/* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
	 ** stores the total number of pages on the freelist. */
	n = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+36)
	if n >= mxPage {
		return _sqlite3CorruptError(tls, int32(79764))
	}
	if n > uint32(0) {
		searchList = uint8(0) /* If the free-list must be searched for 'nearby' */
		nSearch = uint32(0)   /* Count of the number of search attempts */
		/* If eMode==BTALLOC_EXACT and a query of the pointer-map
		 ** shows that the page 'nearby' is somewhere on the free-list, then
		 ** the entire-list will be searched for that page.
		 */
		if libc.Int32FromUint8(eMode) == int32(BTALLOC_EXACT) {
			if nearby <= mxPage {
				rc = _ptrmapGet(tls, pBt, nearby, bp+4, uintptr(0))
				if rc != 0 {
					return rc
				}
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp + 4))) == int32(PTRMAP_FREEPAGE) {
					searchList = uint8(1)
				}
			}
		} else {
			if libc.Int32FromUint8(eMode) == int32(BTALLOC_LE) {
				searchList = uint8(1)
			}
		}
		/* Decrement the free-list count by 1. Set iTrunk to the index of the
		 ** first free-list trunk page. iPrevTrunk is initially 1.
		 */
		rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FpDbPage)
		if rc != 0 {
			return rc
		}
		_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+36, n-uint32(1))
		/* The code within this loop is run only once if the 'searchList' variable
		 ** is not true. Otherwise, it runs once for each trunk-page on the
		 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
		 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
		 */
		for cond := true; cond; cond = searchList != 0 {
			pPrevTrunk = **(**uintptr)(__ccgo_up(bp))
			if pPrevTrunk != 0 {
				/* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
				 ** is the page number of the next freelist trunk page in the list or
				 ** zero if this is the last freelist trunk page. */
				iTrunk = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPrevTrunk)).FaData)
			} else {
				/* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
				 ** stores the page number of the first page of the freelist, or zero if
				 ** the freelist is empty. */
				iTrunk = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32)
			}
			if v2 = iTrunk > mxPage; !v2 {
				v1 = nSearch
				nSearch = nSearch + 1
			}
			if v2 || v1 > n {
				rc = _sqlite3CorruptError(tls, int32(79820))
			} else {
				rc = _btreeGetUnusedPage(tls, pBt, iTrunk, bp, 0)
			}
			if rc != 0 {
				**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
				goto end_allocate_page
			}
			/* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
			 ** is the number of leaf page pointers to follow. */
			k = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+4)
			if k == uint32(0) && !(searchList != 0) {
				/* The trunk has no leaves and the list is not being searched.
				 ** So extract the trunk page itself and use it as the newly
				 ** allocated page */
				rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
				if rc != 0 {
					goto end_allocate_page
				}
				**(**TPgno)(__ccgo_up(pPgno)) = iTrunk
				libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData, uint32(4))
				**(**uintptr)(__ccgo_up(ppPage)) = **(**uintptr)(__ccgo_up(bp))
				**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
			} else {
				if k > (*TBtShared)(unsafe.Pointer(pBt)).FusableSize/libc.Uint32FromInt32(4)-libc.Uint32FromInt32(2) {
					/* Value of k is out of range.  Database corruption */
					rc = _sqlite3CorruptError(tls, int32(79849))
					goto end_allocate_page
				} else {
					if searchList != 0 && (nearby == iTrunk || iTrunk < nearby && libc.Int32FromUint8(eMode) == int32(BTALLOC_LE)) {
						/* The list is being searched and this trunk page is the page
						 ** to allocate, regardless of whether it has leaves.
						 */
						**(**TPgno)(__ccgo_up(pPgno)) = iTrunk
						**(**uintptr)(__ccgo_up(ppPage)) = **(**uintptr)(__ccgo_up(bp))
						searchList = uint8(0)
						rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
						if rc != 0 {
							goto end_allocate_page
						}
						if k == uint32(0) {
							if !(pPrevTrunk != 0) {
								libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData, uint32(4))
							} else {
								rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPrevTrunk)).FpDbPage)
								if rc != SQLITE_OK {
									goto end_allocate_page
								}
								libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(pPrevTrunk)).FaData, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData, uint32(4))
							}
						} else {
							iNewTrunk = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+8)
							if iNewTrunk > mxPage {
								rc = _sqlite3CorruptError(tls, int32(79883))
								goto end_allocate_page
							}
							rc = _btreeGetUnusedPage(tls, pBt, iNewTrunk, bp+8, 0)
							if rc != SQLITE_OK {
								goto end_allocate_page
							}
							rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 8)))).FpDbPage)
							if rc != SQLITE_OK {
								_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 8)))
								goto end_allocate_page
							}
							libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 8)))).FaData, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData, uint32(4))
							_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 8)))).FaData+4, k-uint32(1))
							libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 8)))).FaData+8, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+12, (k-uint32(1))*uint32(4))
							_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 8)))
							if !(pPrevTrunk != 0) {
								_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32, iNewTrunk)
							} else {
								rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPrevTrunk)).FpDbPage)
								if rc != 0 {
									goto end_allocate_page
								}
								_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPrevTrunk)).FaData, iNewTrunk)
							}
						}
						**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
					} else {
						if k > uint32(0) {
							aData = (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData
							if nearby > uint32(0) {
								closest = uint32(0)
								if libc.Int32FromUint8(eMode) == int32(BTALLOC_LE) {
									i = uint32(0)
									for {
										if !(i < k) {
											break
										}
										iPage = _sqlite3Get4byte(tls, aData+uintptr(uint32(8)+i*uint32(4)))
										if iPage <= nearby {
											closest = i
											break
										}
										goto _3
									_3:
										;
										i = i + 1
									}
								} else {
									dist = _sqlite3AbsInt32(tls, libc.Int32FromUint32(_sqlite3Get4byte(tls, aData+8)-nearby))
									i = uint32(1)
									for {
										if !(i < k) {
											break
										}
										d2 = _sqlite3AbsInt32(tls, libc.Int32FromUint32(_sqlite3Get4byte(tls, aData+uintptr(uint32(8)+i*uint32(4)))-nearby))
										if d2 < dist {
											closest = i
											dist = d2
										}
										goto _4
									_4:
										;
										i = i + 1
									}
								}
							} else {
								closest = uint32(0)
							}
							iPage = _sqlite3Get4byte(tls, aData+uintptr(uint32(8)+closest*uint32(4)))
							if iPage > mxPage || iPage < uint32(2) {
								rc = _sqlite3CorruptError(tls, int32(79948))
								goto end_allocate_page
							}
							if !(searchList != 0) || (iPage == nearby || iPage < nearby && libc.Int32FromUint8(eMode) == int32(BTALLOC_LE)) {
								**(**TPgno)(__ccgo_up(pPgno)) = iPage
								rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
								if rc != 0 {
									goto end_allocate_page
								}
								if closest < k-uint32(1) {
									libc.Xmemcpy(tls, aData+uintptr(uint32(8)+closest*uint32(4)), aData+uintptr(uint32(4)+k*uint32(4)), uint32(4))
								}
								_sqlite3Put4byte(tls, aData+4, k-uint32(1))
								if !(_btreeGetHasContent(tls, pBt, **(**TPgno)(__ccgo_up(pPgno))) != 0) {
									v5 = int32(PAGER_GET_NOCONTENT)
								} else {
									v5 = 0
								}
								noContent = v5
								rc = _btreeGetUnusedPage(tls, pBt, **(**TPgno)(__ccgo_up(pPgno)), ppPage, noContent)
								if rc == SQLITE_OK {
									rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(ppPage)))).FpDbPage)
									if rc != SQLITE_OK {
										_releasePage(tls, **(**uintptr)(__ccgo_up(ppPage)))
										**(**uintptr)(__ccgo_up(ppPage)) = uintptr(0)
									}
								}
								searchList = uint8(0)
							}
						}
					}
				}
			}
			_releasePage(tls, pPrevTrunk)
			pPrevTrunk = uintptr(0)
		}
	} else {
		if 0 == libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FbDoTruncate) {
			v5 = int32(PAGER_GET_NOCONTENT)
		} else {
			v5 = 0
		}
		/* There are no pages on the freelist, so append a new page to the
		 ** database image.
		 **
		 ** Normally, new pages allocated by this block can be requested from the
		 ** pager layer with the 'no-content' flag set. This prevents the pager
		 ** from trying to read the pages content from disk. However, if the
		 ** current transaction has already run one or more incremental-vacuum
		 ** steps, then the page we are about to allocate may contain content
		 ** that is required in the event of a rollback. In this case, do
		 ** not set the no-content flag. This causes the pager to load and journal
		 ** the current page content before overwriting it.
		 **
		 ** Note that the pager will not actually attempt to load or journal
		 ** content for any page that really does lie past the end of the database
		 ** file on disk. So the effects of disabling the no-content optimization
		 ** here are confined to those pages that lie between the end of the
		 ** database image and the end of the database file.
		 */
		bNoContent = v5
		rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FpDbPage)
		if rc != 0 {
			return rc
		}
		(*TBtShared)(unsafe.Pointer(pBt)).FnPage = (*TBtShared)(unsafe.Pointer(pBt)).FnPage + 1
		if (*TBtShared)(unsafe.Pointer(pBt)).FnPage == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
			(*TBtShared)(unsafe.Pointer(pBt)).FnPage = (*TBtShared)(unsafe.Pointer(pBt)).FnPage + 1
		}
		if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 && _ptrmapPageno(tls, pBt, (*TBtShared)(unsafe.Pointer(pBt)).FnPage) == (*TBtShared)(unsafe.Pointer(pBt)).FnPage {
			/* If *pPgno refers to a pointer-map page, allocate two new pages
			 ** at the end of the file instead of one. The first allocated page
			 ** becomes a new pointer-map page, the second is used by the caller.
			 */
			**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
			rc = _btreeGetUnusedPage(tls, pBt, (*TBtShared)(unsafe.Pointer(pBt)).FnPage, bp+12, bNoContent)
			if rc == SQLITE_OK {
				rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 12)))).FpDbPage)
				_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 12)))
			}
			if rc != 0 {
				return rc
			}
			(*TBtShared)(unsafe.Pointer(pBt)).FnPage = (*TBtShared)(unsafe.Pointer(pBt)).FnPage + 1
			if (*TBtShared)(unsafe.Pointer(pBt)).FnPage == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
				(*TBtShared)(unsafe.Pointer(pBt)).FnPage = (*TBtShared)(unsafe.Pointer(pBt)).FnPage + 1
			}
		}
		_sqlite3Put4byte(tls, uintptr(28)+(*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData, (*TBtShared)(unsafe.Pointer(pBt)).FnPage)
		**(**TPgno)(__ccgo_up(pPgno)) = (*TBtShared)(unsafe.Pointer(pBt)).FnPage
		rc = _btreeGetUnusedPage(tls, pBt, **(**TPgno)(__ccgo_up(pPgno)), ppPage, bNoContent)
		if rc != 0 {
			return rc
		}
		rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(ppPage)))).FpDbPage)
		if rc != SQLITE_OK {
			_releasePage(tls, **(**uintptr)(__ccgo_up(ppPage)))
			**(**uintptr)(__ccgo_up(ppPage)) = uintptr(0)
		}
	}
	goto end_allocate_page
end_allocate_page:
	;
	_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
	_releasePage(tls, pPrevTrunk)
	return rc
}

// C documentation
//
//	/*
//	** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
//	** if we run out of memory.
//	*/
func _allocateCursor(tls *libc.TLS, p uintptr, iCur int32, nField int32, eCurType Tu8) (r uintptr) {
	var nByte Ti64
	var pCx, pMem, v1 uintptr
	_, _, _, _ = nByte, pCx, pMem, v1
	if iCur > 0 {
		v1 = (*TVdbe)(unsafe.Pointer(p)).FaMem + uintptr((*TVdbe)(unsafe.Pointer(p)).FnMem-iCur)*40
	} else {
		v1 = (*TVdbe)(unsafe.Pointer(p)).FaMem
	}
	/* Find the memory cell that will be used to store the blob of memory
	 ** required for this VdbeCursor structure. It is convenient to use a
	 ** vdbe memory cell to manage the memory allocation required for a
	 ** VdbeCursor structure for the following reasons:
	 **
	 **   * Sometimes cursor numbers are used for a couple of different
	 **     purposes in a vdbe program. The different uses might require
	 **     different sized allocations. Memory cells provide growable
	 **     allocations.
	 **
	 **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
	 **     be freed lazily via the sqlite3_release_memory() API. This
	 **     minimizes the number of malloc calls made by the system.
	 **
	 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
	 ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
	 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
	 */
	pMem = v1
	pCx = uintptr(0)
	nByte = libc.Int64FromUint32((uint32(libc.UintptrFromInt32(0)+84)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7)) + libc.Uint32FromInt32(nField+libc.Int32FromInt32(1))*libc.Uint32FromInt64(8))
	if libc.Int32FromUint8(eCurType) == CURTYPE_BTREE {
		nByte = nByte + int64(_sqlite3BtreeCursorSize(tls))
	}
	if **(**uintptr)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FapCsr + uintptr(iCur)*4)) != 0 { /*OPTIMIZATION-IF-FALSE*/
		_sqlite3VdbeFreeCursorNN(tls, p, **(**uintptr)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FapCsr + uintptr(iCur)*4)))
		**(**uintptr)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FapCsr + uintptr(iCur)*4)) = uintptr(0)
	}
	/* There used to be a call to sqlite3VdbeMemClearAndResize() to make sure
	 ** the pMem used to hold space for the cursor has enough storage available
	 ** in pMem->zMalloc.  But for the special case of the aMem[] entries used
	 ** to hold cursors, it is faster to in-line the logic. */
	if int64((*TMem)(unsafe.Pointer(pMem)).FszMalloc) < nByte {
		if (*TMem)(unsafe.Pointer(pMem)).FszMalloc > 0 {
			_sqlite3DbFreeNN(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, (*TMem)(unsafe.Pointer(pMem)).FzMalloc)
		}
		v1 = _sqlite3DbMallocRaw(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, libc.Uint64FromInt64(nByte))
		(*TMem)(unsafe.Pointer(pMem)).FzMalloc = v1
		(*TMem)(unsafe.Pointer(pMem)).Fz = v1
		if (*TMem)(unsafe.Pointer(pMem)).FzMalloc == uintptr(0) {
			(*TMem)(unsafe.Pointer(pMem)).FszMalloc = 0
			return uintptr(0)
		}
		(*TMem)(unsafe.Pointer(pMem)).FszMalloc = int32(nByte)
	}
	v1 = (*TMem)(unsafe.Pointer(pMem)).FzMalloc
	pCx = v1
	**(**uintptr)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FapCsr + uintptr(iCur)*4)) = v1
	libc.Xmemset(tls, pCx, 0, uint32(libc.UintptrFromInt32(0)+32))
	(*TVdbeCursor)(unsafe.Pointer(pCx)).FeCurType = eCurType
	(*TVdbeCursor)(unsafe.Pointer(pCx)).FnField = int16(nField)
	(*TVdbeCursor)(unsafe.Pointer(pCx)).FaOffset = pCx + 84 + uintptr(nField)*4
	if libc.Int32FromUint8(eCurType) == CURTYPE_BTREE {
		*(*uintptr)(unsafe.Pointer(pCx + 36)) = (*TMem)(unsafe.Pointer(pMem)).Fz + uintptr((uint32(libc.UintptrFromInt32(0)+84)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7))+libc.Uint32FromInt32(nField+libc.Int32FromInt32(1))*libc.Uint32FromInt64(8))
		_sqlite3BtreeCursorZero(tls, *(*uintptr)(unsafe.Pointer(pCx + 36)))
	}
	return pCx
}

// C documentation
//
//	/*
//	** Allocate nByte bytes of space from within the B-Tree page passed
//	** as the first argument. Write into *pIdx the index into pPage->aData[]
//	** of the first byte of allocated space. Return either SQLITE_OK or
//	** an error code (usually SQLITE_CORRUPT).
//	**
//	** The caller guarantees that there is sufficient space to make the
//	** allocation.  This routine might need to defragment in order to bring
//	** all the space together, however.  This routine will avoid using
//	** the first two bytes past the cell pointer area since presumably this
//	** allocation is being made in order to insert a new cell, so we will
//	** also end up needing a new cell pointer.
//	*/
func _allocateSpace(tls *libc.TLS, pPage uintptr, nByte int32, pIdx uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var data, pSpace, pTmp uintptr
	var g2, gap, hdr, top, v1 int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _ = data, g2, gap, hdr, pSpace, pTmp, top, v1
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset) /* Local cache of pPage->hdrOffset */
	data = (*TMemPage)(unsafe.Pointer(pPage)).FaData                         /* First byte of cell content area */
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK                                   /* First byte of gap between cell pointers and cell content */
	/* Minimum cell size is 4 */
	gap = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FcellOffset) + int32(2)*libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)
	/* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
	 ** and the reserved space is zero (the usual value for reserved space)
	 ** then the cell content offset of an empty page wants to be 65536.
	 ** However, that integer is too large to be stored in a 2-byte unsigned
	 ** integer, so a value of 0 is used in its place. */
	pTmp = data + uintptr(hdr+int32(5))
	top = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp + 1)))
	if gap > top {
		if top == 0 && (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize == uint32(65536) {
			top = int32(65536)
		} else {
			return _sqlite3CorruptError(tls, int32(75075))
		}
	} else {
		if top > libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize) {
			return _sqlite3CorruptError(tls, int32(75078))
		}
	}
	/* If there is enough space between gap and top for one more cell pointer,
	 ** and if the freelist is not empty, then search the
	 ** freelist looking for a slot big enough to satisfy the request.
	 */
	if (**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(2)))) != 0 || **(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(1)))) != 0) && gap+int32(2) <= top {
		pSpace = _pageFindSlot(tls, pPage, nByte, bp)
		if pSpace != 0 {
			v1 = int32(pSpace) - int32(data)
			g2 = v1
			**(**int32)(__ccgo_up(pIdx)) = v1
			if g2 <= gap {
				return _sqlite3CorruptError(tls, int32(75095))
			} else {
				return SQLITE_OK
			}
		} else {
			if **(**int32)(__ccgo_up(bp)) != 0 {
				return **(**int32)(__ccgo_up(bp))
			}
		}
	}
	/* The request could not be fulfilled using a freelist slot.  Check
	 ** to see if defragmentation is necessary.
	 */
	if gap+int32(2)+nByte > top {
		if int32(4) < (*TMemPage)(unsafe.Pointer(pPage)).FnFree-(int32(2)+nByte) {
			v1 = int32(4)
		} else {
			v1 = (*TMemPage)(unsafe.Pointer(pPage)).FnFree - (int32(2) + nByte)
		}
		**(**int32)(__ccgo_up(bp)) = _defragmentPage(tls, pPage, v1)
		if **(**int32)(__ccgo_up(bp)) != 0 {
			return **(**int32)(__ccgo_up(bp))
		}
		top = (libc.Int32FromUint8(**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)))-int32(1))&int32(0xffff) + int32(1)
	}
	/* Allocate memory from the gap in between the cell pointer array
	 ** and the cell content area.  The btreeComputeFreeSpace() call has already
	 ** validated the freelist.  Given that the freelist is valid, there
	 ** is no way that the allocation can extend off the end of the page.
	 ** The assert() below verifies the previous sentence.
	 */
	top = top - nByte
	**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)))) = libc.Uint8FromInt32(top >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)) = libc.Uint8FromInt32(top)
	**(**int32)(__ccgo_up(pIdx)) = top
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This callback is invoked once for each index when reading the
//	** sqlite_stat1 table.
//	**
//	**     argv[0] = name of the table
//	**     argv[1] = name of the index (might be NULL)
//	**     argv[2] = results of analysis - on integer for each column
//	**
//	** Entries for which argv[1]==NULL simply record the number of rows in
//	** the table.
//	*/
func _analysisLoader(tls *libc.TLS, pData uintptr, argc int32, argv uintptr, NotUsed uintptr) (r int32) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var aiRowEst, pIndex, pInfo, pTable, z uintptr
	var nCol int32
	var _ /* fakeIdx at bp+0 */ TIndex
	_, _, _, _, _, _ = aiRowEst, nCol, pIndex, pInfo, pTable, z
	pInfo = pData
	_ = NotUsed
	_ = argc
	if argv == uintptr(0) || **(**uintptr)(__ccgo_up(argv)) == uintptr(0) || **(**uintptr)(__ccgo_up(argv + 2*4)) == uintptr(0) {
		return 0
	}
	pTable = _sqlite3FindTable(tls, (*TanalysisInfo)(unsafe.Pointer(pInfo)).Fdb, **(**uintptr)(__ccgo_up(argv)), (*TanalysisInfo)(unsafe.Pointer(pInfo)).FzDatabase)
	if pTable == uintptr(0) {
		return 0
	}
	if **(**uintptr)(__ccgo_up(argv + 1*4)) == uintptr(0) {
		pIndex = uintptr(0)
	} else {
		if Xsqlite3_stricmp(tls, **(**uintptr)(__ccgo_up(argv)), **(**uintptr)(__ccgo_up(argv + 1*4))) == 0 {
			pIndex = _sqlite3PrimaryKeyIndex(tls, pTable)
		} else {
			pIndex = _sqlite3FindIndex(tls, (*TanalysisInfo)(unsafe.Pointer(pInfo)).Fdb, **(**uintptr)(__ccgo_up(argv + 1*4)), (*TanalysisInfo)(unsafe.Pointer(pInfo)).FzDatabase)
		}
	}
	z = **(**uintptr)(__ccgo_up(argv + 2*4))
	if pIndex != 0 {
		aiRowEst = uintptr(0)
		nCol = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnKeyCol) + int32(1)
		/* Index.aiRowEst may already be set here if there are duplicate
		 ** sqlite_stat1 entries for this index. In that case just clobber
		 ** the old data with the new instead of allocating a new array.  */
		if (*TIndex)(unsafe.Pointer(pIndex)).FaiRowEst == uintptr(0) {
			(*TIndex)(unsafe.Pointer(pIndex)).FaiRowEst = _sqlite3MallocZero(tls, uint64(uint32(8)*libc.Uint32FromInt32(nCol)))
			if (*TIndex)(unsafe.Pointer(pIndex)).FaiRowEst == uintptr(0) {
				_sqlite3OomFault(tls, (*TanalysisInfo)(unsafe.Pointer(pInfo)).Fdb)
			}
		}
		aiRowEst = (*TIndex)(unsafe.Pointer(pIndex)).FaiRowEst
		libc.SetBitFieldPtr16Uint32(pIndex+56, libc.Uint32FromInt32(0), 2, 0x4)
		_decodeIntArray(tls, z, nCol, aiRowEst, (*TIndex)(unsafe.Pointer(pIndex)).FaiRowLogEst, pIndex)
		libc.SetBitFieldPtr16Uint32(pIndex+56, libc.Uint32FromInt32(1), 7, 0x80)
		if (*TIndex)(unsafe.Pointer(pIndex)).FpPartIdxWhere == uintptr(0) {
			(*TTable)(unsafe.Pointer(pTable)).FnRowLogEst = **(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pIndex)).FaiRowLogEst))
			**(**Tu32)(__ccgo_up(pTable + 28)) |= uint32(TF_HasStat1)
		}
	} else {
		(**(**TIndex)(__ccgo_up(bp))).FszIdxRow = (*TTable)(unsafe.Pointer(pTable)).FszTabRow
		_decodeIntArray(tls, z, int32(1), uintptr(0), pTable+38, bp)
		(*TTable)(unsafe.Pointer(pTable)).FszTabRow = (**(**TIndex)(__ccgo_up(bp))).FszIdxRow
		**(**Tu32)(__ccgo_up(pTable + 28)) |= uint32(TF_HasStat1)
	}
	return 0
}

// C documentation
//
//	/*
//	** Analyze the arguments to aggregate functions.  Create new pAggInfo->aCol[]
//	** entries for columns that are arguments to aggregate functions but which
//	** are not otherwise used.
//	**
//	** The aCol[] entries in AggInfo prior to nAccumulator are columns that
//	** are referenced outside of aggregate functions.  These might be columns
//	** that are part of the GROUP by clause, for example.  Other database engines
//	** would throw an error if there is a column reference that is not in the
//	** GROUP BY clause and that is not part of an aggregate function argument.
//	** But SQLite allows this.
//	**
//	** The aCol[] entries beginning with the aCol[nAccumulator] and following
//	** are column references that are used exclusively as arguments to
//	** aggregate functions.  This routine is responsible for computing
//	** (or recomputing) those aCol[] entries.
//	*/
func _analyzeAggFuncArgs(tls *libc.TLS, pAggInfo uintptr, pNC uintptr) {
	var i int32
	var pExpr uintptr
	_, _ = i, pExpr
	**(**int32)(__ccgo_up(pNC + 24)) |= int32(NC_InAggFunc)
	i = 0
	for {
		if !(i < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnFunc) {
			break
		}
		pExpr = (**(**TAggInfo_func)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc + uintptr(i)*24))).FpFExpr
		_sqlite3ExprAnalyzeAggList(tls, pNC, *(*uintptr)(unsafe.Pointer(pExpr + 20)))
		if (*TExpr)(unsafe.Pointer(pExpr)).FpLeft != 0 {
			_sqlite3ExprAnalyzeAggList(tls, pNC, *(*uintptr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pExpr)).FpLeft + 20)))
		}
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
			_sqlite3ExprAnalyzeAggregates(tls, pNC, (*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy)))).FpFilter)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	**(**int32)(__ccgo_up(pNC + 24)) &= ^libc.Int32FromInt32(NC_InAggFunc)
}

// C documentation
//
//	/*
//	** Locate or create an AutoincInfo structure associated with table pTab
//	** which is in database iDb.  Return the register number for the register
//	** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
//	** table.  (Also return zero when doing a VACUUM since we do not want to
//	** update the AUTOINCREMENT counters during a VACUUM.)
//	**
//	** There is at most one AutoincInfo structure per table even if the
//	** same table is autoincremented multiple times due to inserts within
//	** triggers.  A new AutoincInfo structure is created if this is the
//	** first use of table pTab.  On 2nd and subsequent uses, the original
//	** AutoincInfo structure is used.
//	**
//	** Four consecutive registers are allocated:
//	**
//	**   (1)  The name of the pTab table.
//	**   (2)  The maximum ROWID of pTab.
//	**   (3)  The rowid in sqlite_sequence of pTab
//	**   (4)  The original value of the max ROWID in pTab, or NULL if none
//	**
//	** The 2nd register is the one that is returned.  That is all the
//	** insert routine needs to know about.
//	*/
func _autoIncBegin(tls *libc.TLS, pParse uintptr, iDb int32, pTab uintptr) (r int32) {
	var memId, v2 int32
	var pInfo, pSeqTab, pToplevel, v1 uintptr
	_, _, _, _, _, _ = memId, pInfo, pSeqTab, pToplevel, v1, v2
	memId = 0 /* Register holding maximum rowid */
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_Autoincrement) != uint32(0) && (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmDbFlags&uint32(DBFLAG_Vacuum) == uint32(0) {
		if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
			v1 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
		} else {
			v1 = pParse
		}
		pToplevel = v1
		pSeqTab = (*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FaDb + uintptr(iDb)*16))).FpSchema)).FpSeqTab
		/* Verify that the sqlite_sequence table exists and is an ordinary
		 ** rowid table with exactly two columns.
		 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
		if pSeqTab == uintptr(0) || !((*TTable)(unsafe.Pointer(pSeqTab)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) || libc.Int32FromUint8((*TTable)(unsafe.Pointer(pSeqTab)).FeTabType) == int32(TABTYP_VTAB) || int32((*TTable)(unsafe.Pointer(pSeqTab)).FnCol) != int32(2) {
			(*TParse)(unsafe.Pointer(pParse)).FnErr = (*TParse)(unsafe.Pointer(pParse)).FnErr + 1
			(*TParse)(unsafe.Pointer(pParse)).Frc = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
			return 0
		}
		pInfo = (*TParse)(unsafe.Pointer(pToplevel)).FpAinc
		for pInfo != 0 && (*TAutoincInfo)(unsafe.Pointer(pInfo)).FpTab != pTab {
			pInfo = (*TAutoincInfo)(unsafe.Pointer(pInfo)).FpNext
		}
		if pInfo == uintptr(0) {
			pInfo = _sqlite3DbMallocRawNN(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(16))
			_sqlite3ParserAddCleanup(tls, pToplevel, __ccgo_fp(_sqlite3DbFree), pInfo)
			if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
				return 0
			}
			(*TAutoincInfo)(unsafe.Pointer(pInfo)).FpNext = (*TParse)(unsafe.Pointer(pToplevel)).FpAinc
			(*TParse)(unsafe.Pointer(pToplevel)).FpAinc = pInfo
			(*TAutoincInfo)(unsafe.Pointer(pInfo)).FpTab = pTab
			(*TAutoincInfo)(unsafe.Pointer(pInfo)).FiDb = iDb
			(*TParse)(unsafe.Pointer(pToplevel)).FnMem = (*TParse)(unsafe.Pointer(pToplevel)).FnMem + 1 /* Register to hold name of table */
			v1 = pToplevel + 48
			*(*int32)(unsafe.Pointer(v1)) = *(*int32)(unsafe.Pointer(v1)) + 1
			v2 = *(*int32)(unsafe.Pointer(v1))
			(*TAutoincInfo)(unsafe.Pointer(pInfo)).FregCtr = v2 /* Max rowid register */
			**(**int32)(__ccgo_up(pToplevel + 48)) += int32(2)  /* Rowid in sqlite_sequence + orig max val */
		}
		memId = (*TAutoincInfo)(unsafe.Pointer(pInfo)).FregCtr
	}
	return memId
}

// C documentation
//
//	/*
//	** This routine generates the code needed to write autoincrement
//	** maximum rowid values back into the sqlite_sequence register.
//	** Every statement that might do an INSERT into an autoincrement
//	** table (either directly or through triggers) needs to call this
//	** routine just before the "exit" code.
//	*/
func _autoIncrementEnd(tls *libc.TLS, pParse uintptr) {
	var aOp, db, p, pDb, v uintptr
	var iRec, memId int32
	_, _, _, _, _, _, _ = aOp, db, iRec, memId, p, pDb, v
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	p = (*TParse)(unsafe.Pointer(pParse)).FpAinc
	for {
		if !(p != 0) {
			break
		}
		pDb = (*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr((*TAutoincInfo)(unsafe.Pointer(p)).FiDb)*16
		memId = (*TAutoincInfo)(unsafe.Pointer(p)).FregCtr
		iRec = _sqlite3GetTempReg(tls, pParse)
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Le), memId+int32(2), _sqlite3VdbeCurrentAddr(tls, v)+int32(7), memId)
		_sqlite3OpenTable(tls, pParse, 0, (*TAutoincInfo)(unsafe.Pointer(p)).FiDb, (*TSchema)(unsafe.Pointer((*TDb)(unsafe.Pointer(pDb)).FpSchema)).FpSeqTab, int32(OP_OpenWrite))
		aOp = _sqlite3VdbeAddOpList(tls, v, libc.Int32FromUint32(libc.Uint32FromInt64(20)/libc.Uint32FromInt64(4)), uintptr(unsafe.Pointer(&_autoIncEnd)), _iLn2)
		if aOp == uintptr(0) {
			break
		}
		(**(**TVdbeOp)(__ccgo_up(aOp))).Fp1 = memId + int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 1*20))).Fp2 = memId + int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 2*20))).Fp1 = memId - int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 2*20))).Fp3 = iRec
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp2 = iRec
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp3 = memId + int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp5 = uint16(OPFLAG_APPEND)
		_sqlite3ReleaseTempReg(tls, pParse, iRec)
		goto _1
	_1:
		;
		p = (*TAutoincInfo)(unsafe.Pointer(p)).FpNext
	}
}

// C documentation
//
//	/*
//	** This routine is called prior to sqlite3PagerCommit when a transaction
//	** is committed for an auto-vacuum database.
//	*/
func _autoVacuumCommit(tls *libc.TLS, p uintptr) (r int32) {
	var db, pBt, pPager uintptr
	var iDb, rc int32
	var iFree, nFin, nFree, nOrig, nVac TPgno
	_, _, _, _, _, _, _, _, _, _ = db, iDb, iFree, nFin, nFree, nOrig, nVac, pBt, pPager, rc
	rc = SQLITE_OK
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	pPager = (*TBtShared)(unsafe.Pointer(pBt)).FpPager
	_invalidateAllOverflowCache(tls, pBt)
	if !((*TBtShared)(unsafe.Pointer(pBt)).FincrVacuum != 0) { /* Database size before freeing */
		nOrig = _btreePagecount(tls, pBt)
		if _ptrmapPageno(tls, pBt, nOrig) == nOrig || nOrig == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
			/* It is not possible to create a database for which the final page
			 ** is either a pointer-map page or the pending-byte page. If one
			 ** is encountered, this indicates corruption.
			 */
			return _sqlite3CorruptError(tls, int32(77456))
		}
		nFree = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+36)
		db = (*TBtree)(unsafe.Pointer(p)).Fdb
		if (*Tsqlite3)(unsafe.Pointer(db)).FxAutovacPages != 0 {
			iDb = 0
			for {
				if !(iDb < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
					break
				}
				if (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpBt == p {
					break
				}
				goto _1
			_1:
				;
				iDb = iDb + 1
			}
			nVac = (*(*func(*libc.TLS, uintptr, uintptr, Tu32, Tu32, Tu32) uint32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3)(unsafe.Pointer(db)).FxAutovacPages})))(tls, (*Tsqlite3)(unsafe.Pointer(db)).FpAutovacPagesArg, (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName, nOrig, nFree, (*TBtShared)(unsafe.Pointer(pBt)).FpageSize)
			if nVac > nFree {
				nVac = nFree
			}
			if nVac == uint32(0) {
				return SQLITE_OK
			}
		} else {
			nVac = nFree
		}
		nFin = _finalDbSize(tls, pBt, nOrig, nVac)
		if nFin > nOrig {
			return _sqlite3CorruptError(tls, int32(77483))
		}
		if nFin < nOrig {
			rc = _saveAllCursors(tls, pBt, uint32(0), uintptr(0))
		}
		iFree = nOrig
		for {
			if !(iFree > nFin && rc == SQLITE_OK) {
				break
			}
			rc = _incrVacuumStep(tls, pBt, nFin, iFree, libc.BoolInt32(nVac == nFree))
			goto _2
		_2:
			;
			iFree = iFree - 1
		}
		if (rc == int32(SQLITE_DONE) || rc == SQLITE_OK) && nFree > uint32(0) {
			rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FpDbPage)
			if nVac == nFree {
				_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+32, uint32(0))
				_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+36, uint32(0))
			}
			_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+28, nFin)
			(*TBtShared)(unsafe.Pointer(pBt)).FbDoTruncate = uint8(1)
			(*TBtShared)(unsafe.Pointer(pBt)).FnPage = nFin
		}
		if rc != SQLITE_OK {
			_sqlite3PagerRollback(tls, pPager)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Parameter zSrcData points to a buffer containing the data for
//	** page iSrcPg from the source database. Copy this data into the
//	** destination database.
//	*/
func _backupOnePage(tls *libc.TLS, p uintptr, iSrcPg TPgno, zSrcData uintptr, bUpdate int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iDest TPgno
	var iEnd, iOff Ti64
	var nCopy, nDestPgsz, nSrcPgsz, rc, v1, v3 int32
	var pDestPager, zDestData, zIn, zOut uintptr
	var v5 bool
	var _ /* pDestPg at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _ = iDest, iEnd, iOff, nCopy, nDestPgsz, nSrcPgsz, pDestPager, rc, zDestData, zIn, zOut, v1, v3, v5
	pDestPager = _sqlite3BtreePager(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)
	nSrcPgsz = _sqlite3BtreeGetPageSize(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc)
	nDestPgsz = _sqlite3BtreeGetPageSize(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)
	if nSrcPgsz < nDestPgsz {
		v1 = nSrcPgsz
	} else {
		v1 = nDestPgsz
	}
	nCopy = v1
	iEnd = libc.Int64FromUint32(iSrcPg) * int64(nSrcPgsz)
	rc = SQLITE_OK
	/* This loop runs once for each destination page spanned by the source
	 ** page. For each iteration, variable iOff is set to the byte offset
	 ** of the destination page.
	 */
	iOff = iEnd - int64(nSrcPgsz)
	for {
		if !(rc == SQLITE_OK && iOff < iEnd) {
			break
		}
		**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
		iDest = libc.Uint32FromInt64(iOff/int64(nDestPgsz)) + uint32(1)
		if iDest == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer((*Tsqlite3_backup)(unsafe.Pointer(p)).FpDest)).FpBt)).FpageSize+libc.Uint32FromInt32(1) {
			goto _2
		}
		v1 = _sqlite3PagerGet(tls, pDestPager, iDest, bp, 0)
		rc = v1
		if v5 = SQLITE_OK == v1; v5 {
			v3 = _sqlite3PagerWrite(tls, **(**uintptr)(__ccgo_up(bp)))
			rc = v3
		}
		if v5 && SQLITE_OK == v3 {
			zIn = zSrcData + uintptr(iOff%int64(nSrcPgsz))
			zDestData = _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp)))
			zOut = zDestData + uintptr(iOff%int64(nDestPgsz))
			/* Copy the data from the source page into the destination page.
			 ** Then clear the Btree layer MemPage.isInit flag. Both this module
			 ** and the pager code use this trick (clearing the first byte
			 ** of the page 'extra' space to invalidate the Btree layers
			 ** cached parse of the page). MemPage.isInit is marked
			 ** "MUST BE FIRST" for this purpose.
			 */
			libc.Xmemcpy(tls, zOut, zIn, libc.Uint32FromInt32(nCopy))
			**(**Tu8)(__ccgo_up(_sqlite3PagerGetExtra(tls, **(**uintptr)(__ccgo_up(bp))))) = uint8(0)
			if iOff == 0 && bUpdate == 0 {
				_sqlite3Put4byte(tls, zOut+28, _sqlite3BtreeLastPage(tls, (*Tsqlite3_backup)(unsafe.Pointer(p)).FpSrc))
			}
		}
		_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp)))
		goto _2
	_2:
		;
		iOff = iOff + int64(nDestPgsz)
	}
	return rc
}

// C documentation
//
//	/*
//	** This function is called when the root page of a b-tree structure is
//	** overfull (has one or more overflow pages).
//	**
//	** A new child page is allocated and the contents of the current root
//	** page, including overflow cells, are copied into the child. The root
//	** page is then overwritten to make it an empty page with the right-child
//	** pointer pointing to the new page.
//	**
//	** Before returning, all pointer-map entries corresponding to pages
//	** that the new child-page now contains pointers to are updated. The
//	** entry corresponding to the new right-child pointer of the root
//	** page is also updated.
//	**
//	** If successful, *ppChild is set to contain a reference to the child
//	** page and SQLITE_OK is returned. In this case the caller is required
//	** to call releasePage() on *ppChild exactly once. If an error occurs,
//	** an error code is returned and *ppChild is set to 0.
//	*/
func _balance_deeper(tls *libc.TLS, pRoot uintptr, ppChild uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pBt uintptr
	var _ /* pChild at bp+4 */ uintptr
	var _ /* pgnoChild at bp+8 */ TPgno
	var _ /* rc at bp+0 */ int32
	_ = pBt                                       /* Return value from subprocedures */
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0) /* Pointer to a new child page */
	**(**TPgno)(__ccgo_up(bp + 8)) = uint32(0)    /* Page number of the new child page */
	pBt = (*TMemPage)(unsafe.Pointer(pRoot)).FpBt /* The BTree */
	/* Make pRoot, the root page of the b-tree, writable. Allocate a new
	 ** page that will become the new right-child of pPage. Copy the contents
	 ** of the node stored on pRoot into the new child page.
	 */
	**(**int32)(__ccgo_up(bp)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pRoot)).FpDbPage)
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp)) = _allocateBtreePage(tls, pBt, bp+4, bp+8, (*TMemPage)(unsafe.Pointer(pRoot)).Fpgno, uint8(0))
		_copyNodeContent(tls, pRoot, **(**uintptr)(__ccgo_up(bp + 4)), bp)
		if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
			_ptrmapPut(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8)), uint8(PTRMAP_BTREE), (*TMemPage)(unsafe.Pointer(pRoot)).Fpgno, bp)
		}
	}
	if **(**int32)(__ccgo_up(bp)) != 0 {
		**(**uintptr)(__ccgo_up(ppChild)) = uintptr(0)
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
		return **(**int32)(__ccgo_up(bp))
	}
	/* Copy the overflow cells from pRoot to pChild */
	libc.Xmemcpy(tls, **(**uintptr)(__ccgo_up(bp + 4))+28, pRoot+28, uint32((*TMemPage)(unsafe.Pointer(pRoot)).FnOverflow)*uint32(2))
	libc.Xmemcpy(tls, **(**uintptr)(__ccgo_up(bp + 4))+36, pRoot+36, uint32((*TMemPage)(unsafe.Pointer(pRoot)).FnOverflow)*uint32(4))
	(*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FnOverflow = (*TMemPage)(unsafe.Pointer(pRoot)).FnOverflow
	/* Zero the contents of pRoot. Then install pChild as the right-child. */
	_zeroPage(tls, pRoot, libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FaData))) & ^libc.Int32FromInt32(PTF_LEAF))
	_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pRoot)).FaData+uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pRoot)).FhdrOffset)+int32(8)), **(**TPgno)(__ccgo_up(bp + 8)))
	**(**uintptr)(__ccgo_up(ppChild)) = **(**uintptr)(__ccgo_up(bp + 4))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This version of balance() handles the common special case where
//	** a new entry is being inserted on the extreme right-end of the
//	** tree, in other words, when the new entry will become the largest
//	** entry in the tree.
//	**
//	** Instead of trying to balance the 3 right-most leaf pages, just add
//	** a new page to the right-hand side and put the one new entry in
//	** that page.  This leaves the right side of the tree somewhat
//	** unbalanced.  But odds are that we will be inserting new entries
//	** at the end soon afterwards so the nearly empty page will quickly
//	** fill up.  On average.
//	**
//	** pPage is the leaf page which is the right-most page in the tree.
//	** pParent is its parent.  pPage must have a single overflow entry
//	** which is also the right-most entry on the page.
//	**
//	** The pSpace buffer is used to store a temporary copy of the divider
//	** cell that will be inserted into pParent. Such a cell consists of a 4
//	** byte page number followed by a variable length integer. In other
//	** words, at most 13 bytes. Hence the pSpace buffer must be at
//	** least 13 bytes in size.
//	*/
func _balance_quick(tls *libc.TLS, pParent uintptr, pPage uintptr, pSpace uintptr) (r int32) {
	bp := tls.Alloc(96)
	defer tls.Free(96)
	var pBt, pOut, pStop, v1, v3 uintptr
	var v2 Tu8
	var _ /* b at bp+20 */ TCellArray
	var _ /* pCell at bp+12 */ uintptr
	var _ /* pNew at bp+0 */ uintptr
	var _ /* pgnoNew at bp+8 */ TPgno
	var _ /* rc at bp+4 */ int32
	var _ /* szCell at bp+16 */ Tu16
	_, _, _, _, _, _ = pBt, pOut, pStop, v1, v2, v3
	pBt = (*TMemPage)(unsafe.Pointer(pPage)).FpBt /* Page number of pNew */
	if libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) == 0 {
		return _sqlite3CorruptError(tls, int32(81243))
	} /* dbfuzz001.test */
	/* Allocate a new page. This page will become the right-sibling of
	 ** pPage. Make the parent page writable, so that the new divider cell
	 ** may be inserted. If both these operations are successful, proceed.
	 */
	**(**int32)(__ccgo_up(bp + 4)) = _allocateBtreePage(tls, pBt, bp, bp+8, uint32(0), uint8(0))
	if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK {
		pOut = pSpace + 4
		**(**uintptr)(__ccgo_up(bp + 12)) = **(**uintptr)(__ccgo_up(pPage + 36))
		**(**Tu16)(__ccgo_up(bp + 16)) = (*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxCellSize})))(tls, pPage, **(**uintptr)(__ccgo_up(bp + 12)))
		_zeroPage(tls, **(**uintptr)(__ccgo_up(bp)), libc.Int32FromInt32(PTF_INTKEY)|libc.Int32FromInt32(PTF_LEAFDATA)|libc.Int32FromInt32(PTF_LEAF))
		(**(**TCellArray)(__ccgo_up(bp + 20))).FnCell = int32(1)
		(**(**TCellArray)(__ccgo_up(bp + 20))).FpRef = pPage
		(**(**TCellArray)(__ccgo_up(bp + 20))).FapCell = bp + 12
		(**(**TCellArray)(__ccgo_up(bp + 20))).FszCell = bp + 16
		**(**uintptr)(__ccgo_up(bp + 20 + 16)) = (*TMemPage)(unsafe.Pointer(pPage)).FaDataEnd
		**(**int32)(__ccgo_up(bp + 20 + 40)) = int32(2)
		**(**int32)(__ccgo_up(bp + 20 + 40 + uintptr(libc.Int32FromInt32(NB)*libc.Int32FromInt32(2)-libc.Int32FromInt32(1))*4)) = int32(0x7fffffff)
		**(**int32)(__ccgo_up(bp + 4)) = _rebuildPage(tls, bp+20, 0, int32(1), **(**uintptr)(__ccgo_up(bp)))
		if **(**int32)(__ccgo_up(bp + 4)) != 0 {
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
			return **(**int32)(__ccgo_up(bp + 4))
		}
		(*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnFree = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer(pBt)).FusableSize - uint32((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FcellOffset) - uint32(2) - uint32(**(**Tu16)(__ccgo_up(bp + 16))))
		/* If this is an auto-vacuum database, update the pointer map
		 ** with entries for the new page, and any pointer from the
		 ** cell on the page to an overflow page. If either of these
		 ** operations fails, the return code is set, but the contents
		 ** of the parent page are still manipulated by the code below.
		 ** That is Ok, at this point the parent page is guaranteed to
		 ** be marked as dirty. Returning an error code will cause a
		 ** rollback, undoing any changes made to the parent page.
		 */
		if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
			_ptrmapPut(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8)), uint8(PTRMAP_BTREE), (*TMemPage)(unsafe.Pointer(pParent)).Fpgno, bp+4)
			if libc.Int32FromUint16(**(**Tu16)(__ccgo_up(bp + 16))) > libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FminLocal) {
				_ptrmapPutOvflPtr(tls, **(**uintptr)(__ccgo_up(bp)), **(**uintptr)(__ccgo_up(bp)), **(**uintptr)(__ccgo_up(bp + 12)), bp+4)
			}
		}
		/* Create a divider cell to insert into pParent. The divider cell
		 ** consists of a 4-byte page number (the page number of pPage) and
		 ** a variable length key value (which must be the same value as the
		 ** largest key on pPage).
		 **
		 ** To find the largest key value on pPage, first find the right-most
		 ** cell on pPage. The first two fields of this cell are the
		 ** record-length (a variable length integer at most 32-bits in size)
		 ** and the key value (a variable length integer, may have any value).
		 ** The first of the while(...) loops below skips over the record-length
		 ** field. The second while(...) loop copies the key value from the
		 ** cell on pPage into the pSpace buffer.
		 */
		**(**uintptr)(__ccgo_up(bp + 12)) = (*TMemPage)(unsafe.Pointer(pPage)).FaData + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)-int32(1))))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)-int32(1))) + 1)))))
		pStop = **(**uintptr)(__ccgo_up(bp + 12)) + 9
		for {
			v1 = **(**uintptr)(__ccgo_up(bp + 12))
			**(**uintptr)(__ccgo_up(bp + 12)) = **(**uintptr)(__ccgo_up(bp + 12)) + 1
			if !(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&int32(0x80) != 0 && **(**uintptr)(__ccgo_up(bp + 12)) < pStop) {
				break
			}
		}
		pStop = **(**uintptr)(__ccgo_up(bp + 12)) + 9
		for {
			v1 = **(**uintptr)(__ccgo_up(bp + 12))
			**(**uintptr)(__ccgo_up(bp + 12)) = **(**uintptr)(__ccgo_up(bp + 12)) + 1
			v2 = **(**Tu8)(__ccgo_up(v1))
			v3 = pOut
			pOut = pOut + 1
			**(**Tu8)(__ccgo_up(v3)) = v2
			if !(libc.Int32FromUint8(v2)&int32(0x80) != 0 && **(**uintptr)(__ccgo_up(bp + 12)) < pStop) {
				break
			}
		}
		/* Insert the new divider cell into pParent. */
		if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK {
			**(**int32)(__ccgo_up(bp + 4)) = _insertCell(tls, pParent, libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FnCell), pSpace, int32(pOut)-int32(pSpace), uintptr(0), (*TMemPage)(unsafe.Pointer(pPage)).Fpgno)
		}
		/* Set the right-child pointer of pParent to point to the new page. */
		_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pParent)).FaData+uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FhdrOffset)+int32(8)), **(**TPgno)(__ccgo_up(bp + 8)))
		/* Release the reference to the new page. */
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
	}
	return **(**int32)(__ccgo_up(bp + 4))
}

// C documentation
//
//	/*
//	** This is the default collating function named "BINARY" which is always
//	** available.
//	*/
func _binCollFunc(tls *libc.TLS, NotUsed uintptr, nKey1 int32, pKey1 uintptr, nKey2 int32, pKey2 uintptr) (r int32) {
	var n, rc, v1 int32
	_, _, _ = n, rc, v1
	_ = NotUsed
	if nKey1 < nKey2 {
		v1 = nKey1
	} else {
		v1 = nKey2
	}
	n = v1
	/* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
	 ** strings byte by byte using the memcmp() function from the standard C
	 ** library. */
	rc = libc.Xmemcmp(tls, pKey1, pKey2, libc.Uint32FromInt32(n))
	if rc == 0 {
		rc = nKey1 - nKey2
	}
	return rc
}

// C documentation
//
//	/*
//	** Bind a text or BLOB value.
//	*/
func _bindText(tls *libc.TLS, pStmt uintptr, i int32, zData uintptr, nData Ti64, __ccgo_fp_xDel uintptr, encoding Tu8) (r int32) {
	var p, pVar, v1 uintptr
	var rc int32
	_, _, _, _ = p, pVar, rc, v1
	p = pStmt
	rc = _vdbeUnbind(tls, p, libc.Uint32FromInt32(i-libc.Int32FromInt32(1)))
	if rc == SQLITE_OK {
		/* tag-20240917-01 */
		if zData != uintptr(0) {
			pVar = (*TVdbe)(unsafe.Pointer(p)).FaVar + uintptr(i-int32(1))*40
			if libc.Int32FromUint8(encoding) == int32(SQLITE_UTF8) {
				rc = _sqlite3VdbeMemSetText(tls, pVar, zData, nData, __ccgo_fp_xDel)
			} else {
				if libc.Int32FromUint8(encoding) == int32(SQLITE_UTF8_ZT) {
					/* It is usually consider improper to assert() on an input.
					 ** However, the following assert() is checking for inputs
					 ** that are documented to result in undefined behavior. */
					rc = _sqlite3VdbeMemSetText(tls, pVar, zData, nData, __ccgo_fp_xDel)
					v1 = pVar + 16
					*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_Term))
				} else {
					rc = _sqlite3VdbeMemSetStr(tls, pVar, zData, nData, encoding, __ccgo_fp_xDel)
					if libc.Int32FromUint8(encoding) == 0 {
						(*TMem)(unsafe.Pointer(pVar)).Fenc = (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fenc
					}
				}
			}
			if rc == SQLITE_OK && libc.Int32FromUint8(encoding) != 0 {
				rc = _sqlite3VdbeChangeEncoding(tls, pVar, libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fenc))
			}
			if rc != 0 {
				_sqlite3Error(tls, (*TVdbe)(unsafe.Pointer(p)).Fdb, rc)
				rc = _sqlite3ApiExit(tls, (*TVdbe)(unsafe.Pointer(p)).Fdb, rc)
			}
		}
		Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).Fmutex)
	} else {
		if __ccgo_fp_xDel != libc.UintptrFromInt32(0) && __ccgo_fp_xDel != uintptr(-libc.Int32FromInt32(1)) {
			(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xDel})))(tls, zData)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Attempt to start a new transaction. A write-transaction
//	** is started if the second argument is nonzero, otherwise a read-
//	** transaction.  If the second argument is 2 or more and exclusive
//	** transaction is started, meaning that no other process is allowed
//	** to access the database.  A preexisting transaction may not be
//	** upgraded to exclusive by calling this routine a second time - the
//	** exclusivity flag only works for a new transaction.
//	**
//	** A write-transaction must be started before attempting any
//	** changes to the database.  None of the following routines
//	** will work unless a transaction is started first:
//	**
//	**      sqlite3BtreeCreateTable()
//	**      sqlite3BtreeCreateIndex()
//	**      sqlite3BtreeClearTable()
//	**      sqlite3BtreeDropTable()
//	**      sqlite3BtreeInsert()
//	**      sqlite3BtreeDelete()
//	**      sqlite3BtreeUpdateMeta()
//	**
//	** If an initial attempt to acquire the lock fails because of lock contention
//	** and the database was previously unlocked, then invoke the busy handler
//	** if there is one.  But if there was previously a read-lock, do not
//	** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
//	** returned when there is already a read-lock in order to avoid a deadlock.
//	**
//	** Suppose there are two processes A and B.  A has a read lock and B has
//	** a reserved lock.  B tries to promote to exclusive but is blocked because
//	** of A's read lock.  A tries to promote to reserved but is blocked by B.
//	** One or the other of the two processes must give way or there can be
//	** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
//	** when A already has a read lock, we encourage A to give up and let B
//	** proceed.
//	*/
func _btreeBeginTrans(tls *libc.TLS, p uintptr, wrflag int32, pSchemaVersion uintptr) (r int32) {
	var pBlock, pBt, pIter, pPage1, pPager, v1 uintptr
	var rc, v5 int32
	var v6 bool
	_, _, _, _, _, _, _, _, _ = pBlock, pBt, pIter, pPage1, pPager, rc, v1, v5, v6
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	pPager = (*TBtShared)(unsafe.Pointer(pBt)).FpPager
	rc = SQLITE_OK
	_sqlite3BtreeEnter(tls, p)
	/* If the btree is already in a write-transaction, or it
	 ** is already in a read-transaction and a read-transaction
	 ** is requested, this is a no-op.
	 */
	if libc.Int32FromUint8((*TBtree)(unsafe.Pointer(p)).FinTrans) == int32(TRANS_WRITE) || libc.Int32FromUint8((*TBtree)(unsafe.Pointer(p)).FinTrans) == int32(TRANS_READ) && !(wrflag != 0) {
		goto trans_begun
	}
	if (*Tsqlite3)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).Fdb)).Fflags&uint64(SQLITE_ResetDatabase) != 0 && libc.Int32FromUint8(_sqlite3PagerIsreadonly(tls, pPager)) == 0 {
		v1 = pBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_READ_ONLY))
	}
	/* Write transactions are not possible on a read-only database */
	if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_READ_ONLY) != 0 && wrflag != 0 {
		rc = int32(SQLITE_READONLY)
		goto trans_begun
	}
	pBlock = uintptr(0)
	/* If another database handle has already opened a write transaction
	 ** on this shared-btree structure and a second write transaction is
	 ** requested, return SQLITE_LOCKED.
	 */
	if wrflag != 0 && libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FinTransaction) == int32(TRANS_WRITE) || libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_PENDING) != 0 {
		pBlock = (*TBtree)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpWriter)).Fdb
	} else {
		if wrflag > int32(1) {
			pIter = (*TBtShared)(unsafe.Pointer(pBt)).FpLock
			for {
				if !(pIter != 0) {
					break
				}
				if (*TBtLock)(unsafe.Pointer(pIter)).FpBtree != p {
					pBlock = (*TBtree)(unsafe.Pointer((*TBtLock)(unsafe.Pointer(pIter)).FpBtree)).Fdb
					break
				}
				goto _2
			_2:
				;
				pIter = (*TBtLock)(unsafe.Pointer(pIter)).FpNext
			}
		}
	}
	if pBlock != 0 {
		_sqlite3ConnectionBlocked(tls, (*TBtree)(unsafe.Pointer(p)).Fdb, pBlock)
		rc = libc.Int32FromInt32(SQLITE_LOCKED) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
		goto trans_begun
	}
	/* Any read-only or read-write transaction implies a read-lock on
	 ** page 1. So if some other shared-cache client already has a write-lock
	 ** on page 1, the transaction cannot be opened. */
	rc = _querySharedCacheTableLock(tls, p, uint32(SCHEMA_ROOT), uint8(READ_LOCK))
	if SQLITE_OK != rc {
		goto trans_begun
	}
	v1 = pBt + 24
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_INITIALLY_EMPTY))
	if (*TBtShared)(unsafe.Pointer(pBt)).FnPage == uint32(0) {
		v1 = pBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTS_INITIALLY_EMPTY))
	}
	for cond := true; cond; cond = rc&int32(0xFF) == int32(SQLITE_BUSY) && libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FinTransaction) == TRANS_NONE && _btreeInvokeBusyHandler(tls, pBt) != 0 {
		/* Call lockBtree() until either pBt->pPage1 is populated or
		 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
		 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
		 ** reading page 1 it discovers that the page-size of the database
		 ** file is not pBt->pageSize. In this case lockBtree() will update
		 ** pBt->pageSize to the page-size of the file on disk.
		 */
		for {
			if v6 = (*TBtShared)(unsafe.Pointer(pBt)).FpPage1 == uintptr(0); v6 {
				v5 = _lockBtree(tls, pBt)
				rc = v5
			}
			if !(v6 && SQLITE_OK == v5) {
				break
			}
		}
		if rc == SQLITE_OK && wrflag != 0 {
			if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_READ_ONLY) != 0 {
				rc = int32(SQLITE_READONLY)
			} else {
				rc = _sqlite3PagerBegin(tls, pPager, libc.BoolInt32(wrflag > int32(1)), _sqlite3TempInMemory(tls, (*TBtree)(unsafe.Pointer(p)).Fdb))
				if rc == SQLITE_OK {
					rc = _newDatabase(tls, pBt)
				} else {
					if rc == libc.Int32FromInt32(SQLITE_BUSY)|libc.Int32FromInt32(2)<<libc.Int32FromInt32(8) && libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FinTransaction) == TRANS_NONE {
						/* if there was no transaction opened when this function was
						 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
						 ** code to SQLITE_BUSY. */
						rc = int32(SQLITE_BUSY)
					}
				}
			}
		}
		if rc != SQLITE_OK {
			_ = SQLITE_OK
			_unlockBtreeIfUnused(tls, pBt)
		}
	}
	if rc == SQLITE_OK {
		if libc.Int32FromUint8((*TBtree)(unsafe.Pointer(p)).FinTrans) == TRANS_NONE {
			(*TBtShared)(unsafe.Pointer(pBt)).FnTransaction = (*TBtShared)(unsafe.Pointer(pBt)).FnTransaction + 1
			if (*TBtree)(unsafe.Pointer(p)).Fsharable != 0 {
				(*TBtree)(unsafe.Pointer(p)).Flock.FeLock = uint8(READ_LOCK)
				(*TBtree)(unsafe.Pointer(p)).Flock.FpNext = (*TBtShared)(unsafe.Pointer(pBt)).FpLock
				(*TBtShared)(unsafe.Pointer(pBt)).FpLock = p + 32
			}
		}
		if wrflag != 0 {
			v5 = int32(TRANS_WRITE)
		} else {
			v5 = int32(TRANS_READ)
		}
		(*TBtree)(unsafe.Pointer(p)).FinTrans = libc.Uint8FromInt32(v5)
		if libc.Int32FromUint8((*TBtree)(unsafe.Pointer(p)).FinTrans) > libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FinTransaction) {
			(*TBtShared)(unsafe.Pointer(pBt)).FinTransaction = (*TBtree)(unsafe.Pointer(p)).FinTrans
		}
		if wrflag != 0 {
			pPage1 = (*TBtShared)(unsafe.Pointer(pBt)).FpPage1
			(*TBtShared)(unsafe.Pointer(pBt)).FpWriter = p
			v1 = pBt + 24
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_EXCLUSIVE))
			if wrflag > int32(1) {
				v1 = pBt + 24
				*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTS_EXCLUSIVE))
			}
			/* If the db-size header field is incorrect (as it may be if an old
			 ** client has been writing the database file), update it now. Doing
			 ** this sooner rather than later means the database size can safely
			 ** re-read the database size from page 1 if a savepoint or transaction
			 ** rollback occurs within the transaction.
			 */
			if (*TBtShared)(unsafe.Pointer(pBt)).FnPage != _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+28) {
				rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FpDbPage)
				if rc == SQLITE_OK {
					_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+28, (*TBtShared)(unsafe.Pointer(pBt)).FnPage)
				}
			}
		}
	}
	goto trans_begun
trans_begun:
	;
	if rc == SQLITE_OK {
		if pSchemaVersion != 0 {
			**(**int32)(__ccgo_up(pSchemaVersion)) = libc.Int32FromUint32(_sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+40))
		}
		if wrflag != 0 {
			/* This call makes sure that the pager has the correct number of
			 ** open savepoints. If the second parameter is greater than 0 and
			 ** the sub-journal is not already open, then it will be opened here.
			 */
			rc = _sqlite3PagerOpenSavepoint(tls, pPager, (*Tsqlite3)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).Fdb)).FnSavepoint)
		}
	}
	_sqlite3BtreeLeave(tls, p)
	return rc
}

// C documentation
//
//	/*
//	** Create a new BTree table.  Write into *piTable the page
//	** number for the root page of the new table.
//	**
//	** The type of type is determined by the flags parameter.  Only the
//	** following values of flags are currently in use.  Other values for
//	** flags might not work:
//	**
//	**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
//	**     BTREE_ZERODATA                  Used for SQL indices
//	*/
func _btreeCreateTable(tls *libc.TLS, p uintptr, piTable uintptr, createTabFlags int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var pBt uintptr
	var ptfFlags int32
	var _ /* eType at bp+20 */ Tu8
	var _ /* iPtrPage at bp+24 */ TPgno
	var _ /* pPageMove at bp+16 */ uintptr
	var _ /* pRoot at bp+0 */ uintptr
	var _ /* pgnoMove at bp+12 */ TPgno
	var _ /* pgnoRoot at bp+4 */ TPgno
	var _ /* rc at bp+8 */ int32
	_, _ = pBt, ptfFlags
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt                 /* Page-type flags for the root page of new table */
	if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 { /* The page to move to. */
		/* Creating a new table may probably require moving an existing database
		 ** to make room for the new tables root page. In case this page turns
		 ** out to be an overflow page, delete all overflow page-map caches
		 ** held by open cursors.
		 */
		_invalidateAllOverflowCache(tls, pBt)
		/* Read the value of meta[3] from the database to determine where the
		 ** root page of the new table should go. meta[3] is the largest root-page
		 ** created so far, so the new root-page is (meta[3]+1).
		 */
		_sqlite3BtreeGetMeta(tls, p, int32(BTREE_LARGEST_ROOT_PAGE), bp+4)
		if **(**TPgno)(__ccgo_up(bp + 4)) > _btreePagecount(tls, pBt) {
			return _sqlite3CorruptError(tls, int32(83314))
		}
		**(**TPgno)(__ccgo_up(bp + 4)) = **(**TPgno)(__ccgo_up(bp + 4)) + 1
		/* The new root-page may not be allocated on a pointer-map page, or the
		 ** PENDING_BYTE page.
		 */
		for **(**TPgno)(__ccgo_up(bp + 4)) == _ptrmapPageno(tls, pBt, **(**TPgno)(__ccgo_up(bp + 4))) || **(**TPgno)(__ccgo_up(bp + 4)) == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
			**(**TPgno)(__ccgo_up(bp + 4)) = **(**TPgno)(__ccgo_up(bp + 4)) + 1
		}
		/* Allocate a page. The page that currently resides at pgnoRoot will
		 ** be moved to the allocated page (unless the allocated page happens
		 ** to reside at pgnoRoot).
		 */
		**(**int32)(__ccgo_up(bp + 8)) = _allocateBtreePage(tls, pBt, bp+16, bp+12, **(**TPgno)(__ccgo_up(bp + 4)), uint8(BTALLOC_EXACT))
		if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
			return **(**int32)(__ccgo_up(bp + 8))
		}
		if **(**TPgno)(__ccgo_up(bp + 12)) != **(**TPgno)(__ccgo_up(bp + 4)) {
			/* pgnoRoot is the page that will be used for the root-page of
			 ** the new table (assuming an error did not occur). But we were
			 ** allocated pgnoMove. If required (i.e. if it was not allocated
			 ** by extending the file), the current page at position pgnoMove
			 ** is already journaled.
			 */
			**(**Tu8)(__ccgo_up(bp + 20)) = uint8(0)
			**(**TPgno)(__ccgo_up(bp + 24)) = uint32(0)
			/* Save the positions of any open cursors. This is required in
			 ** case they are holding a reference to an xFetch reference
			 ** corresponding to page pgnoRoot.  */
			**(**int32)(__ccgo_up(bp + 8)) = _saveAllCursors(tls, pBt, uint32(0), uintptr(0))
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 16)))
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp + 8))
			}
			/* Move the page currently at pgnoRoot to pgnoMove. */
			**(**int32)(__ccgo_up(bp + 8)) = _btreeGetPage(tls, pBt, **(**TPgno)(__ccgo_up(bp + 4)), bp, 0)
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp + 8))
			}
			**(**int32)(__ccgo_up(bp + 8)) = _ptrmapGet(tls, pBt, **(**TPgno)(__ccgo_up(bp + 4)), bp+20, bp+24)
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp + 20))) == int32(PTRMAP_ROOTPAGE) || libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp + 20))) == int32(PTRMAP_FREEPAGE) {
				**(**int32)(__ccgo_up(bp + 8)) = _sqlite3CorruptError(tls, int32(83362))
			}
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
				return **(**int32)(__ccgo_up(bp + 8))
			}
			**(**int32)(__ccgo_up(bp + 8)) = _relocatePage(tls, pBt, **(**uintptr)(__ccgo_up(bp)), **(**Tu8)(__ccgo_up(bp + 20)), **(**TPgno)(__ccgo_up(bp + 24)), **(**TPgno)(__ccgo_up(bp + 12)), 0)
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
			/* Obtain the page at pgnoRoot */
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp + 8))
			}
			**(**int32)(__ccgo_up(bp + 8)) = _btreeGetPage(tls, pBt, **(**TPgno)(__ccgo_up(bp + 4)), bp, 0)
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp + 8))
			}
			**(**int32)(__ccgo_up(bp + 8)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
			if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
				_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
				return **(**int32)(__ccgo_up(bp + 8))
			}
		} else {
			**(**uintptr)(__ccgo_up(bp)) = **(**uintptr)(__ccgo_up(bp + 16))
		}
		/* Update the pointer-map and meta-data with the new root-page number. */
		_ptrmapPut(tls, pBt, **(**TPgno)(__ccgo_up(bp + 4)), uint8(PTRMAP_ROOTPAGE), uint32(0), bp+8)
		if **(**int32)(__ccgo_up(bp + 8)) != 0 {
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
			return **(**int32)(__ccgo_up(bp + 8))
		}
		/* When the new root page was allocated, page 1 was made writable in
		 ** order either to increase the database filesize, or to decrement the
		 ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
		 */
		**(**int32)(__ccgo_up(bp + 8)) = _sqlite3BtreeUpdateMeta(tls, p, int32(4), **(**TPgno)(__ccgo_up(bp + 4)))
		if **(**int32)(__ccgo_up(bp + 8)) != 0 {
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
			return **(**int32)(__ccgo_up(bp + 8))
		}
	} else {
		**(**int32)(__ccgo_up(bp + 8)) = _allocateBtreePage(tls, pBt, bp, bp+4, uint32(1), uint8(0))
		if **(**int32)(__ccgo_up(bp + 8)) != 0 {
			return **(**int32)(__ccgo_up(bp + 8))
		}
	}
	if createTabFlags&int32(BTREE_INTKEY) != 0 {
		ptfFlags = libc.Int32FromInt32(PTF_INTKEY) | libc.Int32FromInt32(PTF_LEAFDATA) | libc.Int32FromInt32(PTF_LEAF)
	} else {
		ptfFlags = libc.Int32FromInt32(PTF_ZERODATA) | libc.Int32FromInt32(PTF_LEAF)
	}
	_zeroPage(tls, **(**uintptr)(__ccgo_up(bp)), ptfFlags)
	_sqlite3PagerUnref(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
	**(**TPgno)(__ccgo_up(piTable)) = **(**TPgno)(__ccgo_up(bp + 4))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Erase all information in a table and add the root of the table to
//	** the freelist.  Except, the root of the principle table (the one on
//	** page 1) is never added to the freelist.
//	**
//	** This routine will fail with SQLITE_LOCKED if there are any open
//	** cursors on the table.
//	**
//	** If AUTOVACUUM is enabled and the page at iTable is not the last
//	** root page in the database file, then the last root page
//	** in the database file is moved into the slot formerly occupied by
//	** iTable and that last slot formerly occupied by the last root page
//	** is added to the freelist instead of iTable.  In this say, all
//	** root pages are kept at the beginning of the database file, which
//	** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
//	** page number that used to be the last root page in the file before
//	** the move.  If no page gets moved, *piMoved is set to 0.
//	** The last root page is recorded in meta[3] and the value of
//	** meta[3] is updated by this procedure.
//	*/
func _btreeDropTable(tls *libc.TLS, p uintptr, iTable TPgno, piMoved uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pBt uintptr
	var _ /* maxRootPgno at bp+8 */ TPgno
	var _ /* pMove at bp+12 */ uintptr
	var _ /* pPage at bp+4 */ uintptr
	var _ /* rc at bp+0 */ int32
	_ = pBt
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	if iTable > _btreePagecount(tls, pBt) {
		return _sqlite3CorruptError(tls, int32(83563))
	}
	**(**int32)(__ccgo_up(bp)) = _sqlite3BtreeClearTable(tls, p, libc.Int32FromUint32(iTable), uintptr(0))
	if **(**int32)(__ccgo_up(bp)) != 0 {
		return **(**int32)(__ccgo_up(bp))
	}
	**(**int32)(__ccgo_up(bp)) = _btreeGetPage(tls, pBt, iTable, bp+4, 0)
	if **(**int32)(__ccgo_up(bp)) != 0 {
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
		return **(**int32)(__ccgo_up(bp))
	}
	**(**int32)(__ccgo_up(piMoved)) = 0
	if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
		_sqlite3BtreeGetMeta(tls, p, int32(BTREE_LARGEST_ROOT_PAGE), bp+8)
		if iTable == **(**TPgno)(__ccgo_up(bp + 8)) {
			/* If the table being dropped is the table with the largest root-page
			 ** number in the database, put the root page on the free list.
			 */
			_freePage(tls, **(**uintptr)(__ccgo_up(bp + 4)), bp)
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp))
			}
		} else {
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
			**(**int32)(__ccgo_up(bp)) = _btreeGetPage(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8)), bp+12, 0)
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp))
			}
			**(**int32)(__ccgo_up(bp)) = _relocatePage(tls, pBt, **(**uintptr)(__ccgo_up(bp + 12)), uint8(PTRMAP_ROOTPAGE), uint32(0), iTable, 0)
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 12)))
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp))
			}
			**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
			**(**int32)(__ccgo_up(bp)) = _btreeGetPage(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8)), bp+12, 0)
			_freePage(tls, **(**uintptr)(__ccgo_up(bp + 12)), bp)
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 12)))
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp))
			}
			**(**int32)(__ccgo_up(piMoved)) = libc.Int32FromUint32(**(**TPgno)(__ccgo_up(bp + 8)))
		}
		/* Set the new 'max-root-page' value in the database header. This
		 ** is the old value less one, less one more if that happens to
		 ** be a root-page number, less one again if that is the
		 ** PENDING_BYTE_PAGE.
		 */
		**(**TPgno)(__ccgo_up(bp + 8)) = **(**TPgno)(__ccgo_up(bp + 8)) - 1
		for **(**TPgno)(__ccgo_up(bp + 8)) == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) || _ptrmapPageno(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8))) == **(**TPgno)(__ccgo_up(bp + 8)) {
			**(**TPgno)(__ccgo_up(bp + 8)) = **(**TPgno)(__ccgo_up(bp + 8)) - 1
		}
		**(**int32)(__ccgo_up(bp)) = _sqlite3BtreeUpdateMeta(tls, p, int32(4), **(**TPgno)(__ccgo_up(bp + 8)))
	} else {
		_freePage(tls, **(**uintptr)(__ccgo_up(bp + 4)), bp)
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/* Overwrite content from pX into pDest.  Only do the write if the
//	** content is different from what is already there.
//	*/
func _btreeOverwriteContent(tls *libc.TLS, pPage uintptr, pDest uintptr, pX uintptr, iOffset int32, iAmt int32) (r int32) {
	var i, nData, rc, rc1, rc2 int32
	_, _, _, _, _ = i, nData, rc, rc1, rc2
	nData = (*TBtreePayload)(unsafe.Pointer(pX)).FnData - iOffset
	if nData <= 0 {
		i = 0
		for {
			if !(i < iAmt && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pDest + uintptr(i)))) == 0) {
				break
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		if i < iAmt {
			rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
			if rc != 0 {
				return rc
			}
			libc.Xmemset(tls, pDest+uintptr(i), 0, libc.Uint32FromInt32(iAmt-i))
		}
	} else {
		if nData < iAmt {
			/* Mixed read data and zeros at the end.  Make a recursive call
			 ** to write the zeros then fall through to write the real data */
			rc1 = _btreeOverwriteContent(tls, pPage, pDest+uintptr(nData), pX, iOffset+nData, iAmt-nData)
			if rc1 != 0 {
				return rc1
			}
			iAmt = nData
		}
		if libc.Xmemcmp(tls, pDest, (*TBtreePayload)(unsafe.Pointer(pX)).FpData+uintptr(iOffset), libc.Uint32FromInt32(iAmt)) != 0 {
			rc2 = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
			if rc2 != 0 {
				return rc2
			}
			/* In a corrupt database, it is possible for the source and destination
			 ** buffers to overlap.  This is harmless since the database is already
			 ** corrupt but it does cause valgrind and ASAN warnings.  So use
			 ** memmove(). */
			libc.Xmemmove(tls, pDest, (*TBtreePayload)(unsafe.Pointer(pX)).FpData+uintptr(iOffset), libc.Uint32FromInt32(iAmt))
		}
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This is common tail processing for btreeParseCellPtr() and
//	** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
//	** on a single B-tree page.  Make necessary adjustments to the CellInfo
//	** structure.
//	*/
func _btreeParseCellAdjustSizeForOverflow(tls *libc.TLS, pPage uintptr, pCell uintptr, pInfo uintptr) {
	var maxLocal, minLocal, surplus int32
	_, _, _ = maxLocal, minLocal, surplus /* Overflow payload available for local storage */
	minLocal = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FminLocal)
	maxLocal = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal)
	surplus = libc.Int32FromUint32(libc.Uint32FromInt32(minLocal) + ((*TCellInfo)(unsafe.Pointer(pInfo)).FnPayload-libc.Uint32FromInt32(minLocal))%((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize-uint32(4)))
	if surplus <= maxLocal {
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal = libc.Uint16FromInt32(surplus)
	} else {
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal = libc.Uint16FromInt32(minLocal)
	}
	(*TCellInfo)(unsafe.Pointer(pInfo)).FnSize = libc.Uint16FromInt32(libc.Int32FromUint16(libc.Uint16FromInt32(t__predefined_ptrdiff_t((*TCellInfo)(unsafe.Pointer(pInfo)).FpPayload+uintptr((*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal))-int32(pCell))) + int32(4))
}

func _btreeParseCellPtr(tls *libc.TLS, pPage uintptr, pCell uintptr, pInfo uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nPayload Tu64
	var pEnd, pIter, v1 uintptr
	var x, v2 Tu8
	var _ /* iKey at bp+0 */ Tu64
	_, _, _, _, _, _ = nPayload, pEnd, pIter, x, v1, v2 /* Extracted Key value */
	pIter = pCell
	/* The next block of code is equivalent to:
	 **
	 **     pIter += getVarint32(pIter, nPayload);
	 **
	 ** The code is inlined to avoid a function call.
	 */
	nPayload = uint64(**(**Tu8)(__ccgo_up(pIter)))
	if nPayload >= uint64(0x80) {
		pEnd = pIter + 8
		nPayload = nPayload & uint64(0x7f)
		for cond := true; cond; cond = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIter))) >= int32(0x80) && pIter < pEnd {
			pIter = pIter + 1
			v1 = pIter
			nPayload = nPayload<<libc.Int32FromInt32(7) | libc.Uint64FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&libc.Int32FromInt32(0x7f))
		}
		nPayload = nPayload & uint64(0xffffffff)
	}
	pIter = pIter + 1
	/* The next block of code is equivalent to:
	 **
	 **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
	 **
	 ** The code is inlined and the loop is unrolled for performance.
	 ** This routine is a high-runner.
	 */
	**(**Tu64)(__ccgo_up(bp)) = uint64(**(**Tu8)(__ccgo_up(pIter)))
	if **(**Tu64)(__ccgo_up(bp)) >= uint64(0x80) {
		pIter = pIter + 1
		v1 = pIter
		v2 = **(**Tu8)(__ccgo_up(v1))
		x = v2
		**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(v2)
		if libc.Int32FromUint8(x) >= int32(0x80) {
			pIter = pIter + 1
			v1 = pIter
			v2 = **(**Tu8)(__ccgo_up(v1))
			x = v2
			**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(v2)
			if libc.Int32FromUint8(x) >= int32(0x80) {
				pIter = pIter + 1
				v1 = pIter
				v2 = **(**Tu8)(__ccgo_up(v1))
				x = v2
				**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(0x10204000) ^ uint64(v2)
				if libc.Int32FromUint8(x) >= int32(0x80) {
					pIter = pIter + 1
					v1 = pIter
					v2 = **(**Tu8)(__ccgo_up(v1))
					x = v2
					**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(0x4000) ^ uint64(v2)
					if libc.Int32FromUint8(x) >= int32(0x80) {
						pIter = pIter + 1
						v1 = pIter
						v2 = **(**Tu8)(__ccgo_up(v1))
						x = v2
						**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(0x4000) ^ uint64(v2)
						if libc.Int32FromUint8(x) >= int32(0x80) {
							pIter = pIter + 1
							v1 = pIter
							v2 = **(**Tu8)(__ccgo_up(v1))
							x = v2
							**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(0x4000) ^ uint64(v2)
							if libc.Int32FromUint8(x) >= int32(0x80) {
								pIter = pIter + 1
								v1 = pIter
								v2 = **(**Tu8)(__ccgo_up(v1))
								x = v2
								**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(7) ^ uint64(0x4000) ^ uint64(v2)
								if libc.Int32FromUint8(x) >= int32(0x80) {
									pIter = pIter + 1
									v1 = pIter
									**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(8) ^ uint64(0x8000) ^ uint64(**(**Tu8)(__ccgo_up(v1)))
								}
							}
						}
					}
				}
			} else {
				**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp)) ^ uint64(0x204000)
			}
		} else {
			**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp)) ^ uint64(0x4000)
		}
	}
	pIter = pIter + 1
	(*TCellInfo)(unsafe.Pointer(pInfo)).FnKey = **(**Ti64)(__ccgo_up(bp))
	(*TCellInfo)(unsafe.Pointer(pInfo)).FnPayload = uint32(nPayload)
	(*TCellInfo)(unsafe.Pointer(pInfo)).FpPayload = pIter
	if nPayload <= uint64((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
		/* This is the (easy) common case where the entire payload fits
		 ** on the local page.  No overflow is required.
		 */
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnSize = libc.Uint16FromInt32(libc.Int32FromUint16(uint16(nPayload)) + libc.Int32FromUint16(libc.Uint16FromInt32(int32(pIter)-int32(pCell))))
		if libc.Int32FromUint16((*TCellInfo)(unsafe.Pointer(pInfo)).FnSize) < int32(4) {
			(*TCellInfo)(unsafe.Pointer(pInfo)).FnSize = uint16(4)
		}
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal = uint16(nPayload)
	} else {
		_btreeParseCellAdjustSizeForOverflow(tls, pPage, pCell, pInfo)
	}
}

func _btreeParseCellPtrIndex(tls *libc.TLS, pPage uintptr, pCell uintptr, pInfo uintptr) {
	var nPayload Tu32
	var pEnd, pIter, v1 uintptr
	_, _, _, _ = nPayload, pEnd, pIter, v1 /* Number of bytes of cell payload */
	pIter = pCell + uintptr((*TMemPage)(unsafe.Pointer(pPage)).FchildPtrSize)
	nPayload = uint32(**(**Tu8)(__ccgo_up(pIter)))
	if nPayload >= uint32(0x80) {
		pEnd = pIter + 8
		nPayload = nPayload & uint32(0x7f)
		for cond := true; cond; cond = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIter))) >= int32(0x80) && pIter < pEnd {
			pIter = pIter + 1
			v1 = pIter
			nPayload = nPayload<<libc.Int32FromInt32(7) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&libc.Int32FromInt32(0x7f))
		}
	}
	pIter = pIter + 1
	(*TCellInfo)(unsafe.Pointer(pInfo)).FnKey = libc.Int64FromUint32(nPayload)
	(*TCellInfo)(unsafe.Pointer(pInfo)).FnPayload = nPayload
	(*TCellInfo)(unsafe.Pointer(pInfo)).FpPayload = pIter
	if nPayload <= uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
		/* This is the (easy) common case where the entire payload fits
		 ** on the local page.  No overflow is required.
		 */
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnSize = libc.Uint16FromInt32(libc.Int32FromUint16(uint16(nPayload)) + libc.Int32FromUint16(libc.Uint16FromInt32(int32(pIter)-int32(pCell))))
		if libc.Int32FromUint16((*TCellInfo)(unsafe.Pointer(pInfo)).FnSize) < int32(4) {
			(*TCellInfo)(unsafe.Pointer(pInfo)).FnSize = uint16(4)
		}
		(*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal = uint16(nPayload)
	} else {
		_btreeParseCellAdjustSizeForOverflow(tls, pPage, pCell, pInfo)
	}
}

// C documentation
//
//	/*
//	** The following routines are implementations of the MemPage.xCellSize
//	** method.
//	**
//	** Compute the total number of bytes that a Cell needs in the cell
//	** data area of the btree-page.  The return number includes the cell
//	** data header and the local payload, but not any overflow page or
//	** the space used by the cell pointer.
//	**
//	** cellSizePtrNoPayload()    =>   table internal nodes
//	** cellSizePtrTableLeaf()    =>   table leaf nodes
//	** cellSizePtr()             =>   index internal nodes
//	** cellSizeIdxLeaf()         =>   index leaf nodes
//	*/
func _cellSizePtr(tls *libc.TLS, pPage uintptr, pCell uintptr) (r Tu16) {
	var minLocal int32
	var nSize Tu32
	var pEnd, pIter, v1 uintptr
	_, _, _, _, _ = minLocal, nSize, pEnd, pIter, v1
	pIter = pCell + uintptr(4) /* Size value to return */
	nSize = uint32(**(**Tu8)(__ccgo_up(pIter)))
	if nSize >= uint32(0x80) {
		pEnd = pIter + 8
		nSize = nSize & uint32(0x7f)
		for cond := true; cond; cond = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIter))) >= int32(0x80) && pIter < pEnd {
			pIter = pIter + 1
			v1 = pIter
			nSize = nSize<<libc.Int32FromInt32(7) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&libc.Int32FromInt32(0x7f))
		}
	}
	pIter = pIter + 1
	if nSize <= uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
		nSize = nSize + libc.Uint32FromInt32(int32(pIter)-int32(pCell))
	} else {
		minLocal = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FminLocal)
		nSize = libc.Uint32FromInt32(minLocal) + (nSize-libc.Uint32FromInt32(minLocal))%((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize-uint32(4))
		if nSize > uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
			nSize = libc.Uint32FromInt32(minLocal)
		}
		nSize = nSize + libc.Uint32FromInt32(int32(4)+libc.Int32FromUint16(libc.Uint16FromInt32(int32(pIter)-int32(pCell))))
	}
	return uint16(nSize)
}

func _cellSizePtrIdxLeaf(tls *libc.TLS, pPage uintptr, pCell uintptr) (r Tu16) {
	var minLocal int32
	var nSize Tu32
	var pEnd, pIter, v1 uintptr
	_, _, _, _, _ = minLocal, nSize, pEnd, pIter, v1
	pIter = pCell /* Size value to return */
	nSize = uint32(**(**Tu8)(__ccgo_up(pIter)))
	if nSize >= uint32(0x80) {
		pEnd = pIter + 8
		nSize = nSize & uint32(0x7f)
		for cond := true; cond; cond = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIter))) >= int32(0x80) && pIter < pEnd {
			pIter = pIter + 1
			v1 = pIter
			nSize = nSize<<libc.Int32FromInt32(7) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&libc.Int32FromInt32(0x7f))
		}
	}
	pIter = pIter + 1
	if nSize <= uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
		nSize = nSize + libc.Uint32FromInt32(int32(pIter)-int32(pCell))
		if nSize < uint32(4) {
			nSize = uint32(4)
		}
	} else {
		minLocal = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FminLocal)
		nSize = libc.Uint32FromInt32(minLocal) + (nSize-libc.Uint32FromInt32(minLocal))%((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize-uint32(4))
		if nSize > uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
			nSize = libc.Uint32FromInt32(minLocal)
		}
		nSize = nSize + libc.Uint32FromInt32(int32(4)+libc.Int32FromUint16(libc.Uint16FromInt32(int32(pIter)-int32(pCell))))
	}
	return uint16(nSize)
}

func _cellSizePtrNoPayload(tls *libc.TLS, pPage uintptr, pCell uintptr) (r Tu16) {
	var pEnd, pIter, v1 uintptr
	_, _, _ = pEnd, pIter, v1
	pIter = pCell + uintptr(4) /* End mark for a varint */
	_ = pPage
	pEnd = pIter + uintptr(9)
	for {
		v1 = pIter
		pIter = pIter + 1
		if !(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&int32(0x80) != 0 && pIter < pEnd) {
			break
		}
	}
	return libc.Uint16FromInt32(int32(pIter) - int32(pCell))
}

func _cellSizePtrTableLeaf(tls *libc.TLS, pPage uintptr, pCell uintptr) (r Tu16) {
	var minLocal int32
	var nSize Tu32
	var pEnd, pIter, v1, v11, v13, v2, v3, v5, v7, v9 uintptr
	var v10, v12, v14, v16, v4, v6, v8 bool
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = minLocal, nSize, pEnd, pIter, v1, v10, v11, v12, v13, v14, v16, v2, v3, v4, v5, v6, v7, v8, v9
	pIter = pCell /* Size value to return */
	nSize = uint32(**(**Tu8)(__ccgo_up(pIter)))
	if nSize >= uint32(0x80) {
		pEnd = pIter + 8
		nSize = nSize & uint32(0x7f)
		for cond := true; cond; cond = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIter))) >= int32(0x80) && pIter < pEnd {
			pIter = pIter + 1
			v1 = pIter
			nSize = nSize<<libc.Int32FromInt32(7) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&libc.Int32FromInt32(0x7f))
		}
	}
	pIter = pIter + 1
	/* pIter now points at the 64-bit integer key value, a variable length
	 ** integer. The following block moves pIter to point at the first byte
	 ** past the end of the key value. */
	v1 = pIter
	pIter = pIter + 1
	if v4 = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1)))&int32(0x80) != 0; v4 {
		v2 = pIter
		pIter = pIter + 1
	}
	if v6 = v4 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v2)))&int32(0x80) != 0; v6 {
		v3 = pIter
		pIter = pIter + 1
	}
	if v8 = v6 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v3)))&int32(0x80) != 0; v8 {
		v5 = pIter
		pIter = pIter + 1
	}
	if v10 = v8 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v5)))&int32(0x80) != 0; v10 {
		v7 = pIter
		pIter = pIter + 1
	}
	if v12 = v10 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v7)))&int32(0x80) != 0; v12 {
		v9 = pIter
		pIter = pIter + 1
	}
	if v14 = v12 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v9)))&int32(0x80) != 0; v14 {
		v11 = pIter
		pIter = pIter + 1
	}
	if v16 = v14 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v11)))&int32(0x80) != 0; v16 {
		v13 = pIter
		pIter = pIter + 1
	}
	if v16 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v13)))&int32(0x80) != 0 {
		pIter = pIter + 1
	}
	if nSize <= uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
		nSize = nSize + libc.Uint32FromInt32(int32(pIter)-int32(pCell))
		if nSize < uint32(4) {
			nSize = uint32(4)
		}
	} else {
		minLocal = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FminLocal)
		nSize = libc.Uint32FromInt32(minLocal) + (nSize-libc.Uint32FromInt32(minLocal))%((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize-uint32(4))
		if nSize > uint32((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
			nSize = libc.Uint32FromInt32(minLocal)
		}
		nSize = nSize + libc.Uint32FromInt32(int32(4)+libc.Int32FromUint16(libc.Uint16FromInt32(int32(pIter)-int32(pCell))))
	}
	return uint16(nSize)
}

// C documentation
//
//	/*
//	** The char() function takes zero or more arguments, each of which is
//	** an integer.  It constructs a string where each character of the string
//	** is the unicode character for the corresponding integer argument.
//	*/
func _charFunc(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	var c uint32
	var i int32
	var x Tsqlite3_int64
	var z, zOut, v1 uintptr
	_, _, _, _, _, _ = c, i, x, z, zOut, v1
	v1 = Xsqlite3_malloc64(tls, libc.Uint64FromInt32(argc*int32(4)+int32(1)))
	z = v1
	zOut = v1
	if z == uintptr(0) {
		Xsqlite3_result_error_nomem(tls, context)
		return
	}
	i = 0
	for {
		if !(i < argc) {
			break
		}
		x = Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(argv + uintptr(i)*4)))
		if x < 0 || x > int64(0x10ffff) {
			x = int64(0xfffd)
		}
		c = libc.Uint32FromInt64(x & libc.Int64FromInt32(0x1fffff))
		if c < uint32(0x00080) {
			v1 = zOut
			zOut = zOut + 1
			**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0xFF))
		} else {
			if c < uint32(0x00800) {
				v1 = zOut
				zOut = zOut + 1
				**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xC0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x1F))))
				v1 = zOut
				zOut = zOut + 1
				**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
			} else {
				if c < uint32(0x10000) {
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xE0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x0F))))
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
				} else {
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xF0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(18)&libc.Uint32FromInt32(0x07))))
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x3F))))
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
					v1 = zOut
					zOut = zOut + 1
					**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
				}
			}
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	**(**uint8)(__ccgo_up(zOut)) = uint8(0)
	Xsqlite3_result_text64(tls, context, z, libc.Uint64FromInt32(int32(zOut)-int32(z)), __ccgo_fp(Xsqlite3_free), uint8(SQLITE_UTF8_ZT))
}

// C documentation
//
//	/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
//	*  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
//	** expression node references any of the
//	** columns that are being modified by an UPDATE statement.
//	*/
func _checkConstraintExprNode(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) {
		if int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) >= 0 {
			if **(**int32)(__ccgo_up(*(*uintptr)(unsafe.Pointer(pWalker + 24)) + uintptr((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)*4)) >= 0 {
				v1 = pWalker + 20
				*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(CKCNSTRNT_COLUMN))
			}
		} else {
			v1 = pWalker + 20
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(CKCNSTRNT_ROWID))
		}
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Free the overflow pages associated with the given Cell.
//	*/
func _clearCellOverflow(tls *libc.TLS, pPage uintptr, pCell uintptr, pInfo uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nOvfl, rc, v1 int32
	var ovflPageSize Tu32
	var ovflPgno TPgno
	var pBt, v2 uintptr
	var v3 bool
	var _ /* iNext at bp+0 */ TPgno
	var _ /* pOvfl at bp+4 */ uintptr
	_, _, _, _, _, _, _, _ = nOvfl, ovflPageSize, ovflPgno, pBt, rc, v1, v2, v3
	if pCell+uintptr((*TCellInfo)(unsafe.Pointer(pInfo)).FnSize) > (*TMemPage)(unsafe.Pointer(pPage)).FaDataEnd {
		/* Cell extends past end of page */
		return _sqlite3CorruptError(tls, int32(80222))
	}
	ovflPgno = _sqlite3Get4byte(tls, pCell+uintptr((*TCellInfo)(unsafe.Pointer(pInfo)).FnSize)-uintptr(4))
	pBt = (*TMemPage)(unsafe.Pointer(pPage)).FpBt
	ovflPageSize = (*TBtShared)(unsafe.Pointer(pBt)).FusableSize - uint32(4)
	nOvfl = libc.Int32FromUint32(((*TCellInfo)(unsafe.Pointer(pInfo)).FnPayload - uint32((*TCellInfo)(unsafe.Pointer(pInfo)).FnLocal) + ovflPageSize - uint32(1)) / ovflPageSize)
	for {
		v1 = nOvfl
		nOvfl = nOvfl - 1
		if !(v1 != 0) {
			break
		}
		**(**TPgno)(__ccgo_up(bp)) = uint32(0)
		**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
		if ovflPgno < uint32(2) || ovflPgno > _btreePagecount(tls, pBt) {
			/* 0 is not a legal page number and page 1 cannot be an
			 ** overflow page. Therefore if ovflPgno<2 or past the end of the
			 ** file the database must be corrupt. */
			return _sqlite3CorruptError(tls, int32(80239))
		}
		if nOvfl != 0 {
			rc = _getOverflowPage(tls, pBt, ovflPgno, bp+4, bp)
			if rc != 0 {
				return rc
			}
		}
		if v3 = **(**uintptr)(__ccgo_up(bp + 4)) != 0; !v3 {
			v2 = _btreePageLookup(tls, pBt, ovflPgno)
			**(**uintptr)(__ccgo_up(bp + 4)) = v2
		}
		if (v3 || v2 != uintptr(0)) && _sqlite3PagerPageRefcount(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage) != int32(1) {
			/* There is no reason any cursor should have an outstanding reference
			 ** to an overflow page belonging to a cell that is being deleted/updated.
			 ** So if there exists more than one reference to this page, then it
			 ** must not really be an overflow page and the database must be corrupt.
			 ** It is helpful to detect this before calling freePage2(), as
			 ** freePage2() may zero the page contents if secure-delete mode is
			 ** enabled. If this 'overflow' page happens to be a page that the
			 ** caller is iterating through or using in some other way, this
			 ** can be problematic.
			 */
			rc = _sqlite3CorruptError(tls, int32(80259))
		} else {
			rc = _freePage2(tls, pBt, **(**uintptr)(__ccgo_up(bp + 4)), ovflPgno)
		}
		if **(**uintptr)(__ccgo_up(bp + 4)) != 0 {
			_sqlite3PagerUnref(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage)
		}
		if rc != 0 {
			return rc
		}
		ovflPgno = **(**TPgno)(__ccgo_up(bp))
	}
	return SQLITE_OK
}

/* Call xParseCell to compute the size of a cell.  If the cell contains
** overflow, then invoke cellClearOverflow to clear out that overflow.
** Store the result code (SQLITE_OK or some error code) in rc.
**
** Implemented as macro to force inlining for performance.
 */

// C documentation
//
//	/*
//	** Erase the given database page and all its children.  Return
//	** the page to the freelist.
//	*/
func _clearDatabasePage(tls *libc.TLS, pBt uintptr, pgno TPgno, freePageFlag int32, pnChange uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var hdr, i, v2 int32
	var pCell uintptr
	var _ /* info at bp+8 */ TCellInfo
	var _ /* pPage at bp+0 */ uintptr
	var _ /* rc at bp+4 */ int32
	_, _, _, _ = hdr, i, pCell, v2
	if pgno > _btreePagecount(tls, pBt) {
		return _sqlite3CorruptError(tls, int32(83452))
	}
	**(**int32)(__ccgo_up(bp + 4)) = _getAndInitPage(tls, pBt, pgno, bp, 0)
	if **(**int32)(__ccgo_up(bp + 4)) != 0 {
		return **(**int32)(__ccgo_up(bp + 4))
	}
	if libc.Int32FromUint8((*TBtShared)(unsafe.Pointer(pBt)).FopenFlags)&int32(BTREE_SINGLE) == 0 && _sqlite3PagerPageRefcount(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage) != int32(1)+libc.BoolInt32(pgno == uint32(1)) {
		**(**int32)(__ccgo_up(bp + 4)) = _sqlite3CorruptError(tls, int32(83459))
		goto cleardatabasepage_out
	}
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FhdrOffset)
	i = 0
	for {
		if !(i < libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnCell)) {
			break
		}
		pCell = (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaCellIdx + uintptr(int32(2)*i))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaCellIdx + uintptr(int32(2)*i) + 1)))))
		if !((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Fleaf != 0) {
			**(**int32)(__ccgo_up(bp + 4)) = _clearDatabasePage(tls, pBt, _sqlite3Get4byte(tls, pCell), int32(1), pnChange)
			if **(**int32)(__ccgo_up(bp + 4)) != 0 {
				goto cleardatabasepage_out
			}
		}
		(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FxParseCell})))(tls, **(**uintptr)(__ccgo_up(bp)), pCell, bp+8)
		if uint32((**(**TCellInfo)(__ccgo_up(bp + 8))).FnLocal) != (**(**TCellInfo)(__ccgo_up(bp + 8))).FnPayload {
			**(**int32)(__ccgo_up(bp + 4)) = _clearCellOverflow(tls, **(**uintptr)(__ccgo_up(bp)), pCell, bp+8)
		} else {
			**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
		}
		if **(**int32)(__ccgo_up(bp + 4)) != 0 {
			goto cleardatabasepage_out
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	if !((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Fleaf != 0) {
		**(**int32)(__ccgo_up(bp + 4)) = _clearDatabasePage(tls, pBt, _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+uintptr(hdr+int32(8))), int32(1), pnChange)
		if **(**int32)(__ccgo_up(bp + 4)) != 0 {
			goto cleardatabasepage_out
		}
		if (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FintKey != 0 {
			pnChange = uintptr(0)
		}
	}
	if pnChange != 0 {
		**(**Ti64)(__ccgo_up(pnChange)) += libc.Int64FromUint16((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnCell)
	}
	if freePageFlag != 0 {
		_freePage(tls, **(**uintptr)(__ccgo_up(bp)), bp+4)
	} else {
		v2 = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
		**(**int32)(__ccgo_up(bp + 4)) = v2
		if v2 == 0 {
			_zeroPage(tls, **(**uintptr)(__ccgo_up(bp)), libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData + uintptr(hdr))))|int32(PTF_LEAF))
		}
	}
	goto cleardatabasepage_out
cleardatabasepage_out:
	;
	_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
	return **(**int32)(__ccgo_up(bp + 4))
}

// C documentation
//
//	/*
//	** This procedure generates VDBE code for a single invocation of either the
//	** sqlite_detach() or sqlite_attach() SQL user functions.
//	*/
func _codeAttach(tls *libc.TLS, pParse uintptr, type1 int32, pFunc uintptr, pAuthArg uintptr, pFilename uintptr, pDbname uintptr, pKey uintptr) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var db, v, zAuthArg uintptr
	var rc, regArgs int32
	var _ /* sName at bp+0 */ TNameContext
	_, _, _, _, _ = db, rc, regArgs, v, zAuthArg
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	if SQLITE_OK != _sqlite3ReadSchema(tls, pParse) {
		goto attach_end
	}
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		goto attach_end
	}
	libc.Xmemset(tls, bp, 0, uint32(36))
	(**(**TNameContext)(__ccgo_up(bp))).FpParse = pParse
	if SQLITE_OK != _resolveAttachExpr(tls, bp, pFilename) || SQLITE_OK != _resolveAttachExpr(tls, bp, pDbname) || SQLITE_OK != _resolveAttachExpr(tls, bp, pKey) {
		goto attach_end
	}
	if pAuthArg != 0 {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pAuthArg)).Fop) == int32(TK_STRING) {
			zAuthArg = *(*uintptr)(unsafe.Pointer(pAuthArg + 8))
		} else {
			zAuthArg = uintptr(0)
		}
		rc = _sqlite3AuthCheck(tls, pParse, type1, zAuthArg, uintptr(0), uintptr(0))
		if rc != SQLITE_OK {
			goto attach_end
		}
	}
	v = _sqlite3GetVdbe(tls, pParse)
	regArgs = _sqlite3GetTempRange(tls, pParse, int32(4))
	_sqlite3ExprCode(tls, pParse, pFilename, regArgs)
	_sqlite3ExprCode(tls, pParse, pDbname, regArgs+int32(1))
	_sqlite3ExprCode(tls, pParse, pKey, regArgs+int32(2))
	if v != 0 {
		_sqlite3VdbeAddFunctionCall(tls, pParse, 0, regArgs+int32(3)-int32((*TFuncDef)(unsafe.Pointer(pFunc)).FnArg), regArgs+int32(3), int32((*TFuncDef)(unsafe.Pointer(pFunc)).FnArg), pFunc, 0)
		/* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
		 ** statement only). For DETACH, set it to false (expire all existing
		 ** statements).
		 */
		_sqlite3VdbeAddOp1(tls, v, int32(OP_Expire), libc.BoolInt32(type1 == int32(SQLITE_ATTACH)))
	}
	goto attach_end
attach_end:
	;
	_sqlite3ExprDelete(tls, db, pFilename)
	_sqlite3ExprDelete(tls, db, pDbname)
	_sqlite3ExprDelete(tls, db, pKey)
}

// C documentation
//
//	/*
//	** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
//	** a rowid value just read from cursor iIdxCur, open on index pIdx. This
//	** function generates code to do a deferred seek of cursor iCur to the
//	** rowid stored in register iRowid.
//	**
//	** Normally, this is just:
//	**
//	**   OP_DeferredSeek $iCur $iRowid
//	**
//	** Which causes a seek on $iCur to the row with rowid $iRowid.
//	**
//	** However, if the scan currently being coded is a branch of an OR-loop and
//	** the statement currently being coded is a SELECT, then additional information
//	** is added that might allow OP_Column to omit the seek and instead do its
//	** lookup on the index, thus avoiding an expensive seek operation.  To
//	** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
//	** and P4 is set to an array of integers containing one entry for each column
//	** in the table.  For each table column, if the column is the i'th
//	** column of the index, then the corresponding array entry is set to (i+1).
//	** If the column does not appear in the index at all, the array entry is set
//	** to 0.  The OP_Column opcode can check this array to see if the column it
//	** wants is in the index and if it is, it will substitute the index cursor
//	** and column number and continue with those new values, rather than seeking
//	** the table cursor.
//	*/
func _codeDeferredSeek(tls *libc.TLS, pWInfo uintptr, pIdx uintptr, iCur int32, iIdxCur int32) {
	var ai, pParse, pTab, v, v1 uintptr
	var i, x1, x2 int32
	var v2 bool
	_, _, _, _, _, _, _, _, _ = ai, i, pParse, pTab, v, x1, x2, v1, v2
	pParse = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpParse /* Parse context */
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe           /* Vdbe to generate code within */
	libc.SetBitFieldPtr8Uint32(pWInfo+48, libc.Uint32FromInt32(1), 0, 0x1)
	_sqlite3VdbeAddOp3(tls, v, int32(OP_DeferredSeek), iIdxCur, 0, iCur)
	if v2 = libc.Int32FromUint16((*TWhereInfo)(unsafe.Pointer(pWInfo)).FwctrlFlags)&(libc.Int32FromInt32(WHERE_OR_SUBCLAUSE)|libc.Int32FromInt32(WHERE_RIGHT_JOIN)) != 0; v2 {
		if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
			v1 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
		} else {
			v1 = pParse
		}
	}
	if v2 && (*TParse)(unsafe.Pointer(v1)).FwriteMask == uint32(0) {
		pTab = (*TIndex)(unsafe.Pointer(pIdx)).FpTable
		ai = _sqlite3DbMallocZero(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(uint32(4)*libc.Uint32FromInt32(int32((*TTable)(unsafe.Pointer(pTab)).FnCol)+libc.Int32FromInt32(1))))
		if ai != 0 {
			**(**Tu32)(__ccgo_up(ai)) = libc.Uint32FromInt16((*TTable)(unsafe.Pointer(pTab)).FnCol)
			i = 0
			for {
				if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)-int32(1)) {
					break
				}
				x1 = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2)))
				x2 = int32(_sqlite3TableColumnToStorage(tls, pTab, int16(x1)))
				if x1 >= 0 {
					**(**Tu32)(__ccgo_up(ai + uintptr(x2+int32(1))*4)) = libc.Uint32FromInt32(i + int32(1))
				}
				goto _3
			_3:
				;
				i = i + 1
			}
			_sqlite3VdbeChangeP4(tls, v, -int32(1), ai, -int32(15))
		}
	}
}

// C documentation
//
//	/*
//	** Generate code for a single X IN (....) term of the WHERE clause.
//	**
//	** This is a special-case of codeEqualityTerm() that works for IN operators
//	** only.  It is broken out into a subroutine because this case is
//	** uncommon and by splitting it off into a subroutine, the common case
//	** runs faster.
//	**
//	** The current value for the constraint is left in  register iTarget.
//	** This routine sets up a loop that will iterate over all values of X.
//	*/
func _codeINTerm(tls *libc.TLS, pParse uintptr, pTerm uintptr, pLevel uintptr, iEq int32, bRev int32, iTarget int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aiMap, db, pIn, pLoop, pX, pXMod, v uintptr
	var eType, i, iCol, iMap, iOut, nEq, v3, v5 int32
	var _ /* iTab at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aiMap, db, eType, i, iCol, iMap, iOut, nEq, pIn, pLoop, pX, pXMod, v, v3, v5
	pX = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
	eType = int32(IN_INDEX_NOOP)
	pLoop = (*TWhereLevel)(unsafe.Pointer(pLevel)).FpWLoop
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	nEq = 0
	aiMap = uintptr(0)
	if (*TWhereLoop)(unsafe.Pointer(pLoop)).FwsFlags&uint32(WHERE_VIRTUALTABLE) == uint32(0) && (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FpIndex != uintptr(0) && **(**Tu8)(__ccgo_up((*TIndex)(unsafe.Pointer((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FpIndex)).FaSortOrder + uintptr(iEq))) != 0 {
		bRev = libc.BoolInt32(!(bRev != 0))
	}
	i = 0
	for {
		if !(i < iEq) {
			break
		}
		if **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)) != 0 && (*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)))).FpExpr == pX {
			_disableTerm(tls, pLevel, pTerm)
			return
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	i = iEq
	for {
		if !(i < libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pLoop)).FnLTerm)) {
			break
		}
		if (*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)))).FpExpr == pX {
			nEq = nEq + 1
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	**(**int32)(__ccgo_up(bp)) = 0
	if !((*TExpr)(unsafe.Pointer(pX)).Fflags&libc.Uint32FromInt32(EP_xIsSelect) != libc.Uint32FromInt32(0)) || (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pX + 20)))).FpEList)).FnExpr == int32(1) {
		eType = _sqlite3FindInIndex(tls, pParse, pX, uint32(IN_INDEX_LOOP), uintptr(0), uintptr(0), bp)
	} else {
		db = (*TParse)(unsafe.Pointer(pParse)).Fdb
		pXMod = _removeUnindexableInClauseTerms(tls, pParse, iEq, pLoop, pX)
		if !((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0) {
			aiMap = _sqlite3DbMallocZero(tls, db, uint64(uint32(4)*libc.Uint32FromInt32(nEq)))
			eType = _sqlite3FindInIndex(tls, pParse, pXMod, uint32(IN_INDEX_LOOP), uintptr(0), aiMap, bp)
		}
		_sqlite3ExprDelete(tls, db, pXMod)
	}
	if eType == int32(IN_INDEX_INDEX_DESC) {
		bRev = libc.BoolInt32(!(bRev != 0))
	}
	if bRev != 0 {
		v3 = int32(OP_Last)
	} else {
		v3 = int32(OP_Rewind)
	}
	_sqlite3VdbeAddOp2(tls, v, v3, **(**int32)(__ccgo_up(bp)), 0)
	**(**Tu32)(__ccgo_up(pLoop + 40)) |= uint32(WHERE_IN_ABLE)
	if (*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FnIn == 0 {
		(*TWhereLevel)(unsafe.Pointer(pLevel)).FaddrNxt = _sqlite3VdbeMakeLabel(tls, pParse)
	}
	if iEq > 0 && (*TWhereLoop)(unsafe.Pointer(pLoop)).FwsFlags&uint32(WHERE_IN_SEEKSCAN) == uint32(0) {
		**(**Tu32)(__ccgo_up(pLoop + 40)) |= uint32(WHERE_IN_EARLYOUT)
	}
	i = (*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FnIn
	(*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FnIn += nEq
	(*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FaInLoop = _sqlite3WhereRealloc(tls, (*TWhereClause)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpWC)).FpWInfo, (*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FaInLoop, uint64(uint32(20)*libc.Uint32FromInt32((*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FnIn)))
	pIn = (*(*struct {
		FnIn     int32
		FaInLoop uintptr
	})(unsafe.Pointer(pLevel + 68))).FaInLoop
	if pIn != 0 {
		iMap = 0 /* Index in aiMap[] */
		pIn = pIn + uintptr(i)*20
		i = iEq
		for {
			if !(i < libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pLoop)).FnLTerm)) {
				break
			}
			if (*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)))).FpExpr == pX {
				iOut = iTarget + i - iEq
				if eType == int32(IN_INDEX_ROWID) {
					(*TInLoop)(unsafe.Pointer(pIn)).FaddrInTop = _sqlite3VdbeAddOp2(tls, v, int32(OP_Rowid), **(**int32)(__ccgo_up(bp)), iOut)
				} else {
					if aiMap != 0 {
						v5 = iMap
						iMap = iMap + 1
						v3 = **(**int32)(__ccgo_up(aiMap + uintptr(v5)*4))
					} else {
						v3 = 0
					}
					iCol = v3
					(*TInLoop)(unsafe.Pointer(pIn)).FaddrInTop = _sqlite3VdbeAddOp3(tls, v, int32(OP_Column), **(**int32)(__ccgo_up(bp)), iCol, iOut)
				}
				_sqlite3VdbeAddOp1(tls, v, int32(OP_IsNull), iOut)
				if i == iEq {
					(*TInLoop)(unsafe.Pointer(pIn)).FiCur = **(**int32)(__ccgo_up(bp))
					if bRev != 0 {
						v3 = int32(OP_Prev)
					} else {
						v3 = int32(OP_Next)
					}
					(*TInLoop)(unsafe.Pointer(pIn)).FeEndLoopOp = libc.Uint8FromInt32(v3)
					if iEq > 0 {
						(*TInLoop)(unsafe.Pointer(pIn)).FiBase = iTarget - i
						(*TInLoop)(unsafe.Pointer(pIn)).FnPrefix = i
					} else {
						(*TInLoop)(unsafe.Pointer(pIn)).FnPrefix = 0
					}
				} else {
					(*TInLoop)(unsafe.Pointer(pIn)).FeEndLoopOp = uint8(OP_Noop)
				}
				pIn += 20
			}
			goto _4
		_4:
			;
			i = i + 1
		}
		if iEq > 0 && (*TWhereLoop)(unsafe.Pointer(pLoop)).FwsFlags&libc.Uint32FromInt32(libc.Int32FromInt32(WHERE_IN_SEEKSCAN)|libc.Int32FromInt32(WHERE_VIRTUALTABLE)) == uint32(0) {
			_sqlite3VdbeAddOp3(tls, v, int32(OP_SeekHit), (*TWhereLevel)(unsafe.Pointer(pLevel)).FiIdxCur, 0, iEq)
		}
	} else {
		(*(*struct {
			FnIn     int32
			FaInLoop uintptr
		})(unsafe.Pointer(pLevel + 68))).FnIn = 0
	}
	_sqlite3DbFree(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, aiMap)
}

// C documentation
//
//	/*
//	** Code an OP_TableLock instruction for each table locked by the
//	** statement (configured by calls to sqlite3TableLock()).
//	*/
func _codeTableLocks(tls *libc.TLS, pParse uintptr) {
	var i, p1 int32
	var p, pVdbe uintptr
	_, _, _, _ = i, p, p1, pVdbe
	pVdbe = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	i = 0
	for {
		if !(i < (*TParse)(unsafe.Pointer(pParse)).FnTableLock) {
			break
		}
		p = (*TParse)(unsafe.Pointer(pParse)).FaTableLock + uintptr(i)*16
		p1 = (*TTableLock)(unsafe.Pointer(p)).FiDb
		_sqlite3VdbeAddOp4(tls, pVdbe, int32(OP_TableLock), p1, libc.Int32FromUint32((*TTableLock)(unsafe.Pointer(p)).FiTab), libc.Int32FromUint8((*TTableLock)(unsafe.Pointer(p)).FisWriteLock), (*TTableLock)(unsafe.Pointer(p)).FzLockName, -int32(1))
		goto _1
	_1:
		;
		i = i + 1
	}
}

/*
** Return TRUE if the given yDbMask object is empty - if it contains no
** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
** macros when SQLITE_MAX_ATTACHED is greater than 30.
 */

// C documentation
//
//	/*
//	** Return true if any column of pIndex uses the zColl collation
//	*/
func _collationMatch(tls *libc.TLS, zColl uintptr, pIndex uintptr) (r int32) {
	var i int32
	var z uintptr
	_, _ = i, z
	i = 0
	for {
		if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnColumn)) {
			break
		}
		z = **(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pIndex)).FazColl + uintptr(i)*4))
		if 0 == _sqlite3StrICmp(tls, z, zColl) {
			return int32(1)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** Return true if column iCol of table pTab seem like it might be a
//	** good column to use as part of a query-time index.
//	**
//	** Current algorithm (subject to improvement!):
//	**
//	**   1.   If iCol is already the left-most column of some other index,
//	**        then return false.
//	**
//	**   2.   If iCol is part of an existing index that has an aiRowLogEst of
//	**        more than 20, then return false.
//	**
//	**   3.   If no disqualifying conditions above are found, return true.
//	**
//	** 2025-01-03: I experimented with a new rule that returns false if the
//	** the datatype of the column is "BOOLEAN". This did not improve
//	** performance on any queries at hand, but it did burn CPU cycles, so the
//	** idea was not committed.
//	*/
func _columnIsGoodIndexCandidate(tls *libc.TLS, pTab uintptr, iCol int32) (r int32) {
	var j int32
	var pIdx uintptr
	_, _ = j, pIdx
	pIdx = (*TTable)(unsafe.Pointer(pTab)).FpIndex
	for {
		if !(pIdx != uintptr(0)) {
			break
		}
		j = 0
		for {
			if !(j < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)) {
				break
			}
			if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(j)*2))) == iCol {
				if j == 0 {
					return 0
				}
				if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x80>>7)) != 0 && int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiRowLogEst + uintptr(j+int32(1))*2))) > int32(20) {
					return 0
				}
				break
			}
			goto _2
		_2:
			;
			j = j + 1
		}
		goto _1
	_1:
		;
		pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** Check to see if column iCol of the given statement is valid.  If
//	** it is, return a pointer to the Mem for the value of that column.
//	** If iCol is not valid, return a pointer to a Mem which has a value
//	** of NULL.
//	*/
func _columnMem(tls *libc.TLS, pStmt uintptr, i int32) (r uintptr) {
	var pOut, pVm uintptr
	_, _ = pOut, pVm
	pVm = pStmt
	if pVm == uintptr(0) {
		return _columnNullValue(tls)
	}
	Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(pVm)).Fdb)).Fmutex)
	if (*TVdbe)(unsafe.Pointer(pVm)).FpResultRow != uintptr(0) && i < libc.Int32FromUint16((*TVdbe)(unsafe.Pointer(pVm)).FnResColumn) && i >= 0 {
		pOut = (*TVdbe)(unsafe.Pointer(pVm)).FpResultRow + uintptr(i)*40
	} else {
		_sqlite3Error(tls, (*TVdbe)(unsafe.Pointer(pVm)).Fdb, int32(SQLITE_RANGE))
		pOut = _columnNullValue(tls)
	}
	return pOut
}

// C documentation
//
//	/*
//	** Compute the iLimit and iOffset fields of the SELECT based on the
//	** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
//	** that appear in the original SQL statement after the LIMIT and OFFSET
//	** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
//	** are the integer memory register numbers for counters used to compute
//	** the limit and offset.  If there is no limit and/or offset, then
//	** iLimit and iOffset are negative.
//	**
//	** This routine changes the values of iLimit and iOffset only if
//	** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit
//	** and iOffset should have been preset to appropriate default values (zero)
//	** prior to calling this routine.
//	**
//	** The iOffset register (if it exists) is initialized to the value
//	** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
//	** iOffset+1 is initialized to LIMIT+OFFSET.
//	**
//	** Only if pLimit->pLeft!=0 do the limit registers get
//	** redefined.  The UNION ALL operator uses this property to force
//	** the reuse of the same limit and offset registers across multiple
//	** SELECT statements.
//	*/
func _computeLimitRegisters(tls *libc.TLS, pParse uintptr, p uintptr, iBreak int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iLimit, iOffset, v1, v2 int32
	var pLimit, v, v3 uintptr
	var _ /* n at bp+0 */ int32
	_, _, _, _, _, _, _ = iLimit, iOffset, pLimit, v, v1, v2, v3
	v = uintptr(0)
	iLimit = 0
	pLimit = (*TSelect)(unsafe.Pointer(p)).FpLimit
	if (*TSelect)(unsafe.Pointer(p)).FiLimit != 0 {
		return
	}
	/*
	 ** "LIMIT -1" always shows all rows.  There is some
	 ** controversy about what the correct behavior should be.
	 ** The current implementation interprets "LIMIT 0" to mean
	 ** no rows.
	 */
	if pLimit != 0 {
		v3 = pParse + 48
		*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
		v2 = *(*int32)(unsafe.Pointer(v3))
		v1 = v2
		iLimit = v1
		(*TSelect)(unsafe.Pointer(p)).FiLimit = v1
		v = _sqlite3GetVdbe(tls, pParse)
		if _sqlite3ExprIsInteger(tls, (*TExpr)(unsafe.Pointer(pLimit)).FpLeft, bp, pParse) != 0 {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Integer), **(**int32)(__ccgo_up(bp)), iLimit)
			if **(**int32)(__ccgo_up(bp)) == 0 {
				_sqlite3VdbeGoto(tls, v, iBreak)
			} else {
				if **(**int32)(__ccgo_up(bp)) >= 0 && int32((*TSelect)(unsafe.Pointer(p)).FnSelectRow) > int32(_sqlite3LogEst(tls, libc.Uint64FromInt32(**(**int32)(__ccgo_up(bp))))) {
					(*TSelect)(unsafe.Pointer(p)).FnSelectRow = _sqlite3LogEst(tls, libc.Uint64FromInt32(**(**int32)(__ccgo_up(bp))))
					**(**Tu32)(__ccgo_up(p + 4)) |= uint32(SF_FixedLimit)
				}
			}
		} else {
			_sqlite3ExprCode(tls, pParse, (*TExpr)(unsafe.Pointer(pLimit)).FpLeft, iLimit)
			_sqlite3VdbeAddOp1(tls, v, int32(OP_MustBeInt), iLimit)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_IfNot), iLimit, iBreak)
		}
		if (*TExpr)(unsafe.Pointer(pLimit)).FpRight != 0 {
			v3 = pParse + 48
			*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
			v2 = *(*int32)(unsafe.Pointer(v3))
			v1 = v2
			iOffset = v1
			(*TSelect)(unsafe.Pointer(p)).FiOffset = v1
			(*TParse)(unsafe.Pointer(pParse)).FnMem = (*TParse)(unsafe.Pointer(pParse)).FnMem + 1 /* Allocate an extra register for limit+offset */
			_sqlite3ExprCode(tls, pParse, (*TExpr)(unsafe.Pointer(pLimit)).FpRight, iOffset)
			_sqlite3VdbeAddOp1(tls, v, int32(OP_MustBeInt), iOffset)
			_sqlite3VdbeAddOp3(tls, v, int32(OP_OffsetLimit), iLimit, iOffset+int32(1), iOffset)
		}
	}
}

// C documentation
//
//	/*
//	** Compute the maximum number of paths in the solver algorithm, for
//	** queries that have three or more terms in the FROM clause.  Queries with
//	** two or fewer FROM clause terms are handled by the caller.
//	**
//	** Query planning is NP-hard.  We must limit the number of paths at
//	** each step of the solver search algorithm to avoid exponential behavior.
//	**
//	** The value returned is a tuning parameter.  Currently the value is:
//	**
//	**     18    for star queries
//	**     12    otherwise
//	**
//	** For the purposes of this heuristic, a star-query is defined as a query
//	** with a central "fact" table that is joined against multiple
//	** "dimension" tables, subject to the following constraints:
//	**
//	**   (aa)  Only a five-way or larger join is considered for this
//	**         optimization.  If there are fewer than four terms in the FROM
//	**         clause, this heuristic does not apply.
//	**
//	**   (bb)  The join between the fact table and the dimension tables must
//	**         be an INNER join.  CROSS and OUTER JOINs do not qualify.
//	**
//	**   (cc)  A table must have 3 or more dimension tables in order to be
//	**         considered a fact table. (Was 4 prior to 2026-02-10.)
//	**
//	**   (dd)  A table that is a self-join cannot be a dimension table.
//	**         Dimension tables are joined against fact tables.
//	**
//	** SIDE EFFECT:  (and really the whole point of this subroutine)
//	**
//	** If pWInfo describes a star-query, then the cost for SCANs of dimension
//	** WhereLoops is increased to be slightly larger than the cost of a SCAN
//	** in the fact table.  Only SCAN costs are increased.  SEARCH costs are
//	** unchanged. This heuristic helps keep fact tables in outer loops. Without
//	** this heuristic, paths with fact tables in outer loops tend to get pruned
//	** by the mxChoice limit on the number of paths, resulting in poor query
//	** plans.  See the starschema1.test test module for examples of queries
//	** that need this heuristic to find good query plans.
//	**
//	** This heuristic can be completely disabled, so that no query is
//	** considered a star-query, using SQLITE_TESTCTRL_OPTIMIZATION to
//	** disable the SQLITE_StarQuery optimization.  In the CLI, the command
//	** to do that is:  ".testctrl opt -starquery".
//	**
//	** HISTORICAL NOTES:
//	**
//	** This optimization was first added on 2024-05-09 by check-in 38db9b5c83d.
//	** The original optimization reduced the cost and output size estimate for
//	** fact tables to help them move to outer loops.  But months later (as people
//	** started upgrading) performance regression reports started caming in,
//	** including:
//	**
//	**    forum post b18ef983e68d06d1 (2024-12-21)
//	**    forum post 0025389d0860af82 (2025-01-14)
//	**    forum post d87570a145599033 (2025-01-17)
//	**
//	** To address these, the criteria for a star-query was tightened to exclude
//	** cases where the fact and dimensions are separated by an outer join, and
//	** the affect of star-schema detection was changed to increase the rRun cost
//	** on just full table scans of dimension tables, rather than reducing costs
//	** in the all access methods of the fact table.
//	*/
func _computeMxChoice(tls *libc.TLS, pWInfo uintptr) (r int32) {
	var aFromTabs, pFactTab, pStart, pWLoop uintptr
	var iFromIdx, nDep, nLoop, v5 int32
	var m, mSeen, mSelfJoin TBitmask
	var mxRun TLogEst
	_, _, _, _, _, _, _, _, _, _, _, _ = aFromTabs, iFromIdx, m, mSeen, mSelfJoin, mxRun, nDep, nLoop, pFactTab, pStart, pWLoop, v5
	nLoop = libc.Int32FromUint8((*TWhereInfo)(unsafe.Pointer(pWInfo)).FnLevel)                                                                                                                                                                                                                        /* For looping over WhereLoops */
	if nLoop >= int32(4) && !(int32(uint32(*(*uint8)(unsafe.Pointer(pWInfo + 48))&0x10>>4)) != 0) && (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer((*TWhereInfo)(unsafe.Pointer(pWInfo)).FpParse)).Fdb)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_StarQuery)) == uint32(0) { /* Bitmask for candidate fact-table */
		mSelfJoin = uint64(0)                                                   /* Where to start searching for dimension-tables */
		libc.SetBitFieldPtr8Uint32(pWInfo+48, libc.Uint32FromInt32(1), 4, 0x10) /* Only do this computation once */
		/* Look for fact tables with three or more dimensions where the
		 ** dimension tables are not separately from the fact tables by an outer
		 ** or cross join.  Adjust cost weights if found.
		 */
		aFromTabs = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpTabList + 8
		pStart = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpLoops
		iFromIdx = 0
		m = libc.Uint64FromInt32(1)
		for {
			if !(iFromIdx < nLoop) {
				break
			}
			nDep = 0          /* Maximum SCAN cost of a fact table */
			mSeen = uint64(0) /* The candidate fact table */
			pFactTab = aFromTabs + uintptr(iFromIdx)*48
			if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pFactTab)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_OUTER)|libc.Int32FromInt32(JT_CROSS)) != 0 {
				/* If the candidate fact-table is the right table of an outer join
				 ** restrict the search for dimension-tables to be tables to the right
				 ** of the fact-table.  Constraint (bb) */
				if iFromIdx+int32(3) > nLoop {
					break /* ^-- Impossible to reach nDep>=2 - Constraint (cc) */
				}
				for pStart != 0 && libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(pStart)).FiTab) <= iFromIdx {
					pStart = (*TWhereLoop)(unsafe.Pointer(pStart)).FpNextLoop
				}
			}
			pWLoop = pStart
			for {
				if !(pWLoop != 0) {
					break
				}
				if libc.Int32FromUint8((**(**TSrcItem)(__ccgo_up(aFromTabs + uintptr((*TWhereLoop)(unsafe.Pointer(pWLoop)).FiTab)*48))).Ffg.Fjointype)&(libc.Int32FromInt32(JT_OUTER)|libc.Int32FromInt32(JT_CROSS)) != 0 {
					break /* Constraint (bb) */
				}
				if (*TWhereLoop)(unsafe.Pointer(pWLoop)).Fprereq&m != uint64(0) && (*TWhereLoop)(unsafe.Pointer(pWLoop)).FmaskSelf&mSeen == uint64(0) && (*TWhereLoop)(unsafe.Pointer(pWLoop)).FmaskSelf&mSelfJoin == uint64(0) {
					if (**(**TSrcItem)(__ccgo_up(aFromTabs + uintptr((*TWhereLoop)(unsafe.Pointer(pWLoop)).FiTab)*48))).FpSTab == (*TSrcItem)(unsafe.Pointer(pFactTab)).FpSTab {
						mSelfJoin = mSelfJoin | m
					} else {
						nDep = nDep + 1
						mSeen = mSeen | (*TWhereLoop)(unsafe.Pointer(pWLoop)).FmaskSelf
					}
				}
				goto _2
			_2:
				;
				pWLoop = (*TWhereLoop)(unsafe.Pointer(pWLoop)).FpNextLoop
			}
			if nDep <= int32(2) {
				goto _1 /* Constraint (cc) */
			}
			/* If we reach this point, it means that pFactTab is a fact table
			 ** with four or more dimensions connected by inner joins.  Proceed
			 ** to make cost adjustments. */
			libc.SetBitFieldPtr8Uint32(pWInfo+48, libc.Uint32FromInt32(1), 5, 0x20)
			/* Compute the maximum cost of any WhereLoop for the
			 ** fact table plus one epsilon */
			mxRun = int16(-libc.Int32FromInt32(32768))
			pWLoop = pStart
			for {
				if !(pWLoop != 0) {
					break
				}
				if libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(pWLoop)).FiTab) < iFromIdx {
					goto _3
				}
				if libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(pWLoop)).FiTab) > iFromIdx {
					break
				}
				if int32((*TWhereLoop)(unsafe.Pointer(pWLoop)).FrRun) > int32(mxRun) {
					mxRun = (*TWhereLoop)(unsafe.Pointer(pWLoop)).FrRun
				}
				goto _3
			_3:
				;
				pWLoop = (*TWhereLoop)(unsafe.Pointer(pWLoop)).FpNextLoop
			}
			if int32(mxRun) < int32(LOGEST_MAX) {
				mxRun = mxRun + 1
			}
			/* Increase the cost of table scans for dimension tables to be
			 ** slightly more than the maximum cost of the fact table */
			pWLoop = pStart
			for {
				if !(pWLoop != 0) {
					break
				}
				if (*TWhereLoop)(unsafe.Pointer(pWLoop)).FmaskSelf&mSeen == uint64(0) {
					goto _4
				}
				if (*TWhereLoop)(unsafe.Pointer(pWLoop)).FnLTerm != 0 {
					goto _4
				}
				if int32((*TWhereLoop)(unsafe.Pointer(pWLoop)).FrRun) < int32(mxRun) {
					(*TWhereLoop)(unsafe.Pointer(pWLoop)).FrRun = mxRun
				}
				goto _4
			_4:
				;
				pWLoop = (*TWhereLoop)(unsafe.Pointer(pWLoop)).FpNextLoop
			}
			goto _1
		_1:
			;
			iFromIdx = iFromIdx + 1
			m = m << uint64(1)
		}
	}
	if int32(uint32(*(*uint8)(unsafe.Pointer(pWInfo + 48))&0x20>>5)) != 0 {
		v5 = int32(18)
	} else {
		v5 = int32(12)
	}
	return v5
}

// C documentation
//
//	/*
//	** We know that pSrc is an operand of an outer join.  Return true if
//	** pTerm is a constraint that is compatible with that join.
//	**
//	** pTerm must be EP_OuterON if pSrc is the right operand of an
//	** outer join.  pTerm can be either EP_OuterON or EP_InnerON if pSrc
//	** is the left operand of a RIGHT join.
//	**
//	** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
//	** for an example of a WHERE clause constraints that may not be used on
//	** the right table of a RIGHT JOIN because the constraint implies a
//	** not-NULL condition on the left table of the RIGHT JOIN.
//	*/
func _constraintCompatibleWithOuterJoin(tls *libc.TLS, pTerm uintptr, pSrc uintptr) (r int32) {
	/* By caller */
	if !((*TExpr)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON)) != libc.Uint32FromInt32(0)) || *(*int32)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr + 36)) != (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor {
		return 0
	}
	if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSrc)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_LEFT)|libc.Int32FromInt32(JT_RIGHT)) != 0 && (*TExpr)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_InnerON)) != uint32(0) {
		return 0
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** Detect compound SELECT statements that use an ORDER BY clause with
//	** an alternative collating sequence.
//	**
//	**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
//	**
//	** These are rewritten as a subquery:
//	**
//	**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
//	**     ORDER BY ... COLLATE ...
//	**
//	** This transformation is necessary because the multiSelectByMerge() routine
//	** above that generates the code for a compound SELECT with an ORDER BY clause
//	** uses a merge algorithm that requires the same collating sequence on the
//	** result columns as on the ORDER BY clause.  See ticket
//	** http://sqlite.org/src/info/6709574d2a
//	**
//	** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
//	** The UNION ALL operator works fine with multiSelectByMerge() even when
//	** there are COLLATE terms in the ORDER BY.
//	*/
func _convertCompoundSelectToSubquery(tls *libc.TLS, pWalker uintptr, p uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a, db, pNew, pNewSrc, pParse, pX uintptr
	var i int32
	var _ /* dummy at bp+0 */ TToken
	_, _, _, _, _, _, _ = a, db, i, pNew, pNewSrc, pParse, pX
	if (*TSelect)(unsafe.Pointer(p)).FpPrior == uintptr(0) {
		return WRC_Continue
	}
	if (*TSelect)(unsafe.Pointer(p)).FpOrderBy == uintptr(0) {
		return WRC_Continue
	}
	pX = p
	for {
		if !(pX != 0 && (libc.Int32FromUint8((*TSelect)(unsafe.Pointer(pX)).Fop) == int32(TK_ALL) || libc.Int32FromUint8((*TSelect)(unsafe.Pointer(pX)).Fop) == int32(TK_SELECT))) {
			break
		}
		goto _1
	_1:
		;
		pX = (*TSelect)(unsafe.Pointer(pX)).FpPrior
	}
	if pX == uintptr(0) {
		return WRC_Continue
	}
	a = (*TSelect)(unsafe.Pointer(p)).FpOrderBy + 8
	/* If iOrderByCol is already non-zero, then it has already been matched
	 ** to a result column of the SELECT statement. This occurs when the
	 ** SELECT is rewritten for window-functions processing and then passed
	 ** to sqlite3SelectPrep() and similar a second time. The rewriting done
	 ** by this function is not required in this case. */
	if *(*Tu16)(unsafe.Pointer(a + 16)) != 0 {
		return WRC_Continue
	}
	i = (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpOrderBy)).FnExpr - int32(1)
	for {
		if !(i >= 0) {
			break
		}
		if (*TExpr)(unsafe.Pointer((**(**TExprList_item)(__ccgo_up(a + uintptr(i)*20))).FpExpr)).Fflags&uint32(EP_Collate) != 0 {
			break
		}
		goto _2
	_2:
		;
		i = i - 1
	}
	if i < 0 {
		return WRC_Continue
	}
	/* If we reach this point, that means the transformation is required. */
	pParse = (*TWalker)(unsafe.Pointer(pWalker)).FpParse
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	pNew = _sqlite3DbMallocZero(tls, db, uint64(68))
	if pNew == uintptr(0) {
		return int32(WRC_Abort)
	}
	libc.Xmemset(tls, bp, 0, uint32(8))
	pNewSrc = _sqlite3SrcListAppendFromTerm(tls, pParse, uintptr(0), uintptr(0), uintptr(0), bp, pNew, uintptr(0))
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		_sqlite3SrcListDelete(tls, db, pNewSrc)
		return int32(WRC_Abort)
	}
	**(**TSelect)(__ccgo_up(pNew)) = **(**TSelect)(__ccgo_up(p))
	(*TSelect)(unsafe.Pointer(p)).FpSrc = pNewSrc
	(*TSelect)(unsafe.Pointer(p)).FpEList = _sqlite3ExprListAppend(tls, pParse, uintptr(0), _sqlite3Expr(tls, db, int32(TK_ASTERISK), uintptr(0)))
	(*TSelect)(unsafe.Pointer(p)).Fop = uint8(TK_SELECT)
	(*TSelect)(unsafe.Pointer(p)).FpWhere = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpGroupBy = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpHaving = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpOrderBy = uintptr(0)
	(*TSelect)(unsafe.Pointer(p)).FpPrior = uintptr(0)
	(*TSelect)(unsafe.Pointer(p)).FpNext = uintptr(0)
	(*TSelect)(unsafe.Pointer(p)).FpWith = uintptr(0)
	(*TSelect)(unsafe.Pointer(p)).FpWinDefn = uintptr(0)
	**(**Tu32)(__ccgo_up(p + 4)) &= ^libc.Uint32FromInt32(SF_Compound)
	**(**Tu32)(__ccgo_up(p + 4)) |= uint32(SF_Converted)
	(*TSelect)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pNew)).FpPrior)).FpNext = pNew
	(*TSelect)(unsafe.Pointer(pNew)).FpLimit = uintptr(0)
	return WRC_Continue
}

// C documentation
//
//	/*
//	** This function is used to copy the contents of the b-tree node stored
//	** on page pFrom to page pTo. If page pFrom was not a leaf page, then
//	** the pointer-map entries for each child page are updated so that the
//	** parent page stored in the pointer map is page pTo. If pFrom contained
//	** any cells with overflow page pointers, then the corresponding pointer
//	** map entries are also updated so that the parent page is page pTo.
//	**
//	** If pFrom is currently carrying any overflow cells (entries in the
//	** MemPage.apOvfl[] array), they are not copied to pTo.
//	**
//	** Before returning, page pTo is reinitialized using btreeInitPage().
//	**
//	** The performance of this function is not critical. It is only used by
//	** the balance_shallower() and balance_deeper() procedures, neither of
//	** which are called often under normal circumstances.
//	*/
func _copyNodeContent(tls *libc.TLS, pFrom uintptr, pTo uintptr, pRC uintptr) {
	var aFrom, aTo, pBt uintptr
	var iData, iFromHdr, iToHdr, rc, v1 int32
	_, _, _, _, _, _, _, _ = aFrom, aTo, iData, iFromHdr, iToHdr, pBt, rc, v1
	if **(**int32)(__ccgo_up(pRC)) == SQLITE_OK {
		pBt = (*TMemPage)(unsafe.Pointer(pFrom)).FpBt
		aFrom = (*TMemPage)(unsafe.Pointer(pFrom)).FaData
		aTo = (*TMemPage)(unsafe.Pointer(pTo)).FaData
		iFromHdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pFrom)).FhdrOffset)
		if (*TMemPage)(unsafe.Pointer(pTo)).Fpgno == uint32(1) {
			v1 = int32(100)
		} else {
			v1 = 0
		}
		iToHdr = v1
		/* Copy the b-tree node content from page pFrom to page pTo. */
		iData = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aFrom + uintptr(iFromHdr+int32(5)))))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aFrom + uintptr(iFromHdr+int32(5)) + 1)))
		libc.Xmemcpy(tls, aTo+uintptr(iData), aFrom+uintptr(iData), (*TBtShared)(unsafe.Pointer(pBt)).FusableSize-libc.Uint32FromInt32(iData))
		libc.Xmemcpy(tls, aTo+uintptr(iToHdr), aFrom+uintptr(iFromHdr), libc.Uint32FromInt32(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pFrom)).FcellOffset)+int32(2)*libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pFrom)).FnCell)))
		/* Reinitialize page pTo so that the contents of the MemPage structure
		 ** match the new data. The initialization of pTo can actually fail under
		 ** fairly obscure circumstances, even though it is a copy of initialized
		 ** page pFrom.
		 */
		(*TMemPage)(unsafe.Pointer(pTo)).FisInit = uint8(0)
		rc = _btreeInitPage(tls, pTo)
		if rc == SQLITE_OK {
			rc = _btreeComputeFreeSpace(tls, pTo)
		}
		if rc != SQLITE_OK {
			**(**int32)(__ccgo_up(pRC)) = rc
			return
		}
		/* If this is an auto-vacuum database, update the pointer-map entries
		 ** for any b-tree or overflow pages that pTo now contains the pointers to.
		 */
		if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
			**(**int32)(__ccgo_up(pRC)) = _setChildPtrmaps(tls, pTo)
		}
	}
}

// C documentation
//
//	/*
//	** Copy data from a buffer to a page, or from a page to a buffer.
//	**
//	** pPayload is a pointer to data stored on database page pDbPage.
//	** If argument eOp is false, then nByte bytes of data are copied
//	** from pPayload to the buffer pointed at by pBuf. If eOp is true,
//	** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
//	** of data are copied from the buffer pBuf to pPayload.
//	**
//	** SQLITE_OK is returned on success, otherwise an error code.
//	*/
func _copyPayload(tls *libc.TLS, pPayload uintptr, pBuf uintptr, nByte int32, eOp int32, pDbPage uintptr) (r int32) {
	var rc int32
	_ = rc
	if eOp != 0 {
		/* Copy data from buffer to page (a write operation) */
		rc = _sqlite3PagerWrite(tls, pDbPage)
		if rc != SQLITE_OK {
			return rc
		}
		libc.Xmemcpy(tls, pPayload, pBuf, libc.Uint32FromInt32(nByte))
	} else {
		/* Copy data from page to buffer (a read operation) */
		libc.Xmemcpy(tls, pBuf, pPayload, libc.Uint32FromInt32(nByte))
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Create a new aggregate context for p and return a pointer to
//	** its pMem->z element.
//	*/
func _createAggContext(tls *libc.TLS, p uintptr, nByte int32) (r uintptr) {
	var pMem uintptr
	_ = pMem
	pMem = (*Tsqlite3_context)(unsafe.Pointer(p)).FpMem
	if nByte <= 0 {
		_sqlite3VdbeMemSetNull(tls, pMem)
		(*TMem)(unsafe.Pointer(pMem)).Fz = uintptr(0)
	} else {
		_sqlite3VdbeMemClearAndResize(tls, pMem, nByte)
		(*TMem)(unsafe.Pointer(pMem)).Fflags = uint16(MEM_Agg)
		*(*uintptr)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pMem)).Fu)) = (*Tsqlite3_context)(unsafe.Pointer(p)).FpFunc
		if (*TMem)(unsafe.Pointer(pMem)).Fz != 0 {
			libc.Xmemset(tls, (*TMem)(unsafe.Pointer(pMem)).Fz, 0, libc.Uint32FromInt32(nByte))
		}
	}
	return (*TMem)(unsafe.Pointer(pMem)).Fz
}

func _dbReallocFinish(tls *libc.TLS, db uintptr, p uintptr, n Tu64) (r uintptr) {
	var pNew uintptr
	_ = pNew
	pNew = uintptr(0)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
		if _isLookaside(tls, db, p) != 0 {
			pNew = _sqlite3DbMallocRawNN(tls, db, n)
			if pNew != 0 {
				libc.Xmemcpy(tls, pNew, p, libc.Uint32FromInt32(_lookasideMallocSize(tls, db, p)))
				_sqlite3DbFree(tls, db, p)
			}
		} else {
			pNew = _sqlite3Realloc(tls, p, n)
			if !(pNew != 0) {
				_sqlite3OomFault(tls, db)
			}
		}
	}
	return pNew
}

func _dbpageColumn(tls *libc.TLS, pCursor uintptr, ctx uintptr, i int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, pCsr uintptr
	var rc int32
	var _ /* pDbPage at bp+0 */ uintptr
	_, _, _ = db, pCsr, rc
	pCsr = pCursor
	rc = SQLITE_OK
	switch i {
	case 0: /* pgno */
		Xsqlite3_result_int64(tls, ctx, libc.Int64FromUint32((*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno))
	case int32(1): /* data */
		**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
		if (*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno == libc.Uint32FromInt32(_sqlite3PendingByte/(*TDbpageCursor)(unsafe.Pointer(pCsr)).FszPage+libc.Int32FromInt32(1)) {
			/* The pending byte page. Assume it is zeroed out. Attempting to
			 ** request this page from the page is an SQLITE_CORRUPT error. */
			Xsqlite3_result_zeroblob(tls, ctx, (*TDbpageCursor)(unsafe.Pointer(pCsr)).FszPage)
		} else {
			rc = _sqlite3PagerGet(tls, (*TDbpageCursor)(unsafe.Pointer(pCsr)).FpPager, (*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno, bp, 0)
			if rc == SQLITE_OK {
				Xsqlite3_result_blob(tls, ctx, _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp))), (*TDbpageCursor)(unsafe.Pointer(pCsr)).FszPage, uintptr(-libc.Int32FromInt32(1)))
			}
			_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp)))
		}
	default: /* schema */
		db = Xsqlite3_context_db_handle(tls, ctx)
		Xsqlite3_result_text(tls, ctx, (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr((*TDbpageCursor)(unsafe.Pointer(pCsr)).FiDb)*16))).FzDbSName, -int32(1), libc.UintptrFromInt32(0))
		break
	}
	return rc
}

// C documentation
//
//	/*
//	** idxNum:
//	**
//	**     0     schema=main, full table scan
//	**     1     schema=main, pgno=?1
//	**     2     schema=?1, full table scan
//	**     3     schema=?1, pgno=?2
//	**
//	** idxStr is not used
//	*/
func _dbpageFilter(tls *libc.TLS, pCursor uintptr, idxNum int32, idxStr uintptr, argc int32, argv uintptr) (r int32) {
	var db, pBt, pCsr, pTab, zSchema uintptr
	var iPg Ti64
	var rc int32
	_, _, _, _, _, _, _ = db, iPg, pBt, pCsr, pTab, rc, zSchema
	pCsr = pCursor
	pTab = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(pCursor)).FpVtab
	db = (*TDbpageTable)(unsafe.Pointer(pTab)).Fdb
	_ = idxStr
	_ = argc
	/* Default setting is no rows of result */
	(*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno = uint32(1)
	(*TDbpageCursor)(unsafe.Pointer(pCsr)).FmxPgno = uint32(0)
	if idxNum&int32(2) != 0 {
		zSchema = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
		(*TDbpageCursor)(unsafe.Pointer(pCsr)).FiDb = _sqlite3FindDbName(tls, db, zSchema)
		if (*TDbpageCursor)(unsafe.Pointer(pCsr)).FiDb < 0 {
			return SQLITE_OK
		}
	} else {
		(*TDbpageCursor)(unsafe.Pointer(pCsr)).FiDb = 0
	}
	pBt = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr((*TDbpageCursor)(unsafe.Pointer(pCsr)).FiDb)*16))).FpBt
	if pBt == uintptr(0) {
		return SQLITE_OK
	}
	(*TDbpageCursor)(unsafe.Pointer(pCsr)).FpPager = _sqlite3BtreePager(tls, pBt)
	(*TDbpageCursor)(unsafe.Pointer(pCsr)).FszPage = _sqlite3BtreeGetPageSize(tls, pBt)
	(*TDbpageCursor)(unsafe.Pointer(pCsr)).FmxPgno = _sqlite3BtreeLastPage(tls, pBt)
	if idxNum&int32(1) != 0 {
		iPg = Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(argv + uintptr(idxNum>>int32(1))*4)))
		if iPg < int64(1) || iPg > libc.Int64FromUint32((*TDbpageCursor)(unsafe.Pointer(pCsr)).FmxPgno) {
			(*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno = uint32(1)
			(*TDbpageCursor)(unsafe.Pointer(pCsr)).FmxPgno = uint32(0)
		} else {
			(*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno = libc.Uint32FromInt64(iPg)
			(*TDbpageCursor)(unsafe.Pointer(pCsr)).FmxPgno = (*TDbpageCursor)(unsafe.Pointer(pCsr)).Fpgno
		}
	} else {
	}
	if (*TDbpageCursor)(unsafe.Pointer(pCsr)).FpPage1 != 0 {
		_sqlite3PagerUnrefPageOne(tls, (*TDbpageCursor)(unsafe.Pointer(pCsr)).FpPage1)
	}
	rc = _sqlite3PagerGet(tls, (*TDbpageCursor)(unsafe.Pointer(pCsr)).FpPager, uint32(1), pCsr+16, 0)
	return rc
}

// C documentation
//
//	/*
//	** Defragment the page given. This routine reorganizes cells within the
//	** page so that there are no free-blocks on the free-block list.
//	**
//	** Parameter nMaxFrag is the maximum amount of fragmented space that may be
//	** present in the page after this routine returns.
//	**
//	** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
//	** b-tree page so that there are no freeblocks or fragment bytes, all
//	** unused bytes are contained in the unallocated space region, and all
//	** cells are packed tightly at the end of the page.
//	*/
func _defragmentPage(tls *libc.TLS, pPage uintptr, nMaxFrag int32) (r int32) {
	var cbrk, cellOffset, hdr, i, iCellFirst, iCellLast, iCellStart, iFree, iFree2, nCell, pc, size, sz, sz2, top, usableSize int32
	var data, pAddr, pAddr1, pEnd, src, temp uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = cbrk, cellOffset, data, hdr, i, iCellFirst, iCellLast, iCellStart, iFree, iFree2, nCell, pAddr, pAddr1, pEnd, pc, size, src, sz, sz2, temp, top, usableSize /* First cell offset in input */
	data = (*TMemPage)(unsafe.Pointer(pPage)).FaData
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)
	cellOffset = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FcellOffset)
	nCell = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)
	iCellFirst = cellOffset + int32(2)*nCell
	usableSize = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize)
	/* This block handles pages with two or fewer free blocks and nMaxFrag
	 ** or fewer fragmented bytes. In this case it is faster to move the
	 ** two (or one) blocks of cells using memmove() and add the required
	 ** offsets to each pointer in the cell-pointer array than it is to
	 ** reconstruct the entire page.  */
	if libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(7))))) <= nMaxFrag {
		iFree = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(1)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(1)) + 1)))
		if iFree > usableSize-int32(4) {
			return _sqlite3CorruptError(tls, int32(74875))
		}
		if iFree != 0 {
			iFree2 = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree) + 1)))
			if iFree2 > usableSize-int32(4) {
				return _sqlite3CorruptError(tls, int32(74878))
			}
			if 0 == iFree2 || libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree2)))) == 0 && libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree2+int32(1))))) == 0 {
				pEnd = data + uintptr(cellOffset+nCell*int32(2))
				sz2 = 0
				sz = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree+int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree+int32(2)) + 1)))
				top = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)))
				if top >= iFree {
					return _sqlite3CorruptError(tls, int32(74886))
				}
				if iFree2 != 0 {
					if iFree+sz > iFree2 {
						return _sqlite3CorruptError(tls, int32(74889))
					}
					sz2 = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree2+int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFree2+int32(2)) + 1)))
					if iFree2+sz2 > usableSize {
						return _sqlite3CorruptError(tls, int32(74891))
					}
					libc.Xmemmove(tls, data+uintptr(iFree+sz+sz2), data+uintptr(iFree+sz), libc.Uint32FromInt32(iFree2-(iFree+sz)))
					sz = sz + sz2
				} else {
					if iFree+sz > usableSize {
						return _sqlite3CorruptError(tls, int32(74895))
					}
				}
				cbrk = top + sz
				libc.Xmemmove(tls, data+uintptr(cbrk), data+uintptr(top), libc.Uint32FromInt32(iFree-top))
				pAddr = data + uintptr(cellOffset)
				for {
					if !(pAddr < pEnd) {
						break
					}
					pc = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pAddr)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pAddr + 1)))
					if pc < iFree {
						**(**Tu8)(__ccgo_up(pAddr)) = libc.Uint8FromInt32((pc + sz) >> libc.Int32FromInt32(8))
						**(**Tu8)(__ccgo_up(pAddr + 1)) = libc.Uint8FromInt32(pc + sz)
					} else {
						if pc < iFree2 {
							**(**Tu8)(__ccgo_up(pAddr)) = libc.Uint8FromInt32((pc + sz2) >> libc.Int32FromInt32(8))
							**(**Tu8)(__ccgo_up(pAddr + 1)) = libc.Uint8FromInt32(pc + sz2)
						}
					}
					goto _1
				_1:
					;
					pAddr = pAddr + uintptr(2)
				}
				goto defragment_out
			}
		}
	}
	cbrk = usableSize
	iCellLast = usableSize - int32(4)
	iCellStart = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)))
	if nCell > 0 {
		temp = _sqlite3PagerTempSpace(tls, (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FpPager)
		libc.Xmemcpy(tls, temp, data, libc.Uint32FromInt32(usableSize))
		src = temp
		i = 0
		for {
			if !(i < nCell) {
				break
			} /* The i-th cell pointer */
			pAddr1 = data + uintptr(cellOffset+i*int32(2))
			pc = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pAddr1)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pAddr1 + 1)))
			/* These conditions have already been verified in btreeInitPage()
			 ** if PRAGMA cell_size_check=ON.
			 */
			if pc > iCellLast {
				return _sqlite3CorruptError(tls, int32(74928))
			}
			size = libc.Int32FromUint16((*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxCellSize})))(tls, pPage, src+uintptr(pc)))
			cbrk = cbrk - size
			if cbrk < iCellStart || pc+size > usableSize {
				return _sqlite3CorruptError(tls, int32(74934))
			}
			**(**Tu8)(__ccgo_up(pAddr1)) = libc.Uint8FromInt32(cbrk >> libc.Int32FromInt32(8))
			**(**Tu8)(__ccgo_up(pAddr1 + 1)) = libc.Uint8FromInt32(cbrk)
			libc.Xmemcpy(tls, data+uintptr(cbrk), src+uintptr(pc), libc.Uint32FromInt32(size))
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(7)))) = uint8(0)
	goto defragment_out
defragment_out:
	;
	if libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(7)))))+cbrk-iCellFirst != (*TMemPage)(unsafe.Pointer(pPage)).FnFree {
		return _sqlite3CorruptError(tls, int32(74948))
	}
	**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)))) = libc.Uint8FromInt32(cbrk >> libc.Int32FromInt32(8))
	**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)) = libc.Uint8FromInt32(cbrk)
	**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(1)))) = uint8(0)
	**(**uint8)(__ccgo_up(data + uintptr(hdr+int32(2)))) = uint8(0)
	libc.Xmemset(tls, data+uintptr(iCellFirst), 0, libc.Uint32FromInt32(cbrk-iCellFirst))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Remove the memory data structures associated with the given
//	** Table.  No changes are made to disk by this routine.
//	**
//	** This routine just deletes the data structure.  It does not unlink
//	** the table data structure from the hash table.  But it does destroy
//	** memory structures of the indices and foreign keys associated with
//	** the table.
//	**
//	** The db parameter is optional.  It is needed if the Table object
//	** contains lookaside memory.  (Table objects in the schema do not use
//	** lookaside memory, but some ephemeral Table objects do.)  Or the
//	** db parameter can be used with db->pnBytesFreed to measure the memory
//	** used by the Table object.
//	*/
func _deleteTable(tls *libc.TLS, db uintptr, pTable uintptr) {
	var pIndex, pNext, zName uintptr
	_, _, _ = pIndex, pNext, zName
	/* Delete all indices associated with this table. */
	pIndex = (*TTable)(unsafe.Pointer(pTable)).FpIndex
	for {
		if !(pIndex != 0) {
			break
		}
		pNext = (*TIndex)(unsafe.Pointer(pIndex)).FpNext
		if (*Tsqlite3)(unsafe.Pointer(db)).FpnBytesFreed == uintptr(0) && !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTable)).FeTabType) == libc.Int32FromInt32(TABTYP_VTAB)) {
			zName = (*TIndex)(unsafe.Pointer(pIndex)).FzName
			_sqlite3HashInsert(tls, (*TIndex)(unsafe.Pointer(pIndex)).FpSchema+24, zName, uintptr(0))
		}
		_sqlite3FreeIndex(tls, db, pIndex)
		goto _1
	_1:
		;
		pIndex = pNext
	}
	if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTable)).FeTabType) == TABTYP_NORM {
		_sqlite3FkDelete(tls, db, pTable)
	} else {
		if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTable)).FeTabType) == int32(TABTYP_VTAB) {
			_sqlite3VtabClear(tls, db, pTable)
		} else {
			_sqlite3SelectDelete(tls, db, (*(*struct {
				FpSelect uintptr
			})(unsafe.Pointer(&(*TTable)(unsafe.Pointer(pTable)).Fu))).FpSelect)
		}
	}
	/* Delete the Table structure itself.
	 */
	_sqlite3DeleteColumnNames(tls, db, pTable)
	_sqlite3DbFree(tls, db, (*TTable)(unsafe.Pointer(pTable)).FzName)
	_sqlite3DbFree(tls, db, (*TTable)(unsafe.Pointer(pTable)).FzColAff)
	_sqlite3ExprListDelete(tls, db, (*TTable)(unsafe.Pointer(pTable)).FpCheck)
	_sqlite3DbFree(tls, db, pTable)
	/* Verify that no lookaside memory was used by schema tables */
}

// C documentation
//
//	/*
//	** Disable a term in the WHERE clause.  Except, do not disable the term
//	** if it controls a LEFT OUTER JOIN and it did not originate in the ON
//	** or USING clause of that join.
//	**
//	** Consider the term t2.z='ok' in the following queries:
//	**
//	**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
//	**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
//	**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
//	**
//	** The t2.z='ok' is disabled in the in (2) because it originates
//	** in the ON clause.  The term is disabled in (3) because it is not part
//	** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
//	**
//	** Disabling a term causes that term to not be tested in the inner loop
//	** of the join.  Disabling is an optimization.  When terms are satisfied
//	** by indices, we disable them to prevent redundant tests in the inner
//	** loop.  We would get the correct results if nothing were ever disabled,
//	** but joins might run a little slower.  The trick is to disable as much
//	** as we can without disabling too much.  If we disabled in (1), we'd get
//	** the wrong answer.  See ticket #813.
//	**
//	** If all the children of a term are disabled, then that term is also
//	** automatically disabled.  In this way, terms get disabled if derived
//	** virtual terms are tested first.  For example:
//	**
//	**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
//	**      \___________/     \______/     \_____/
//	**         parent          child1       child2
//	**
//	** Only the parent term was in the original WHERE clause.  The child1
//	** and child2 terms were added by the LIKE optimization.  If both of
//	** the virtual child terms are valid, then testing of the parent can be
//	** skipped.
//	**
//	** Usually the parent term is marked as TERM_CODED.  But if the parent
//	** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
//	** The TERM_LIKECOND marking indicates that the term should be coded inside
//	** a conditional such that is only evaluated on the second pass of a
//	** LIKE-optimization loop, when scanning BLOBs instead of strings.
//	*/
func _disableTerm(tls *libc.TLS, pLevel uintptr, pTerm uintptr) {
	var nLoop int32
	var v1 uintptr
	_, _ = nLoop, v1
	nLoop = 0
	for libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_CODED) == 0 && ((*TWhereLevel)(unsafe.Pointer(pLevel)).FiLeftJoin == 0 || (*TExpr)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0)) && (*TWhereLevel)(unsafe.Pointer(pLevel)).FnotReady&(*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqAll == uint64(0) {
		if nLoop != 0 && libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_LIKE) != 0 {
			v1 = pTerm + 10
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(TERM_LIKECOND))
		} else {
			v1 = pTerm + 10
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(TERM_CODED))
		}
		if (*TWhereTerm)(unsafe.Pointer(pTerm)).FiParent < 0 {
			break
		}
		pTerm = (*TWhereClause)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpWC)).Fa + uintptr((*TWhereTerm)(unsafe.Pointer(pTerm)).FiParent)*48
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FnChild = (*TWhereTerm)(unsafe.Pointer(pTerm)).FnChild - 1
		if libc.Int32FromUint8((*TWhereTerm)(unsafe.Pointer(pTerm)).FnChild) != 0 {
			break
		}
		nLoop = nLoop + 1
	}
}

// C documentation
//
//	/*
//	** Check to see if a subquery contains result-set columns that are
//	** never used.  If it does, change the value of those result-set columns
//	** to NULL so that they do not cause unnecessary work to compute.
//	**
//	** Return the number of column that were changed to NULL.
//	*/
func _disableUnusedSubqueryResultColumns(tls *libc.TLS, pItem uintptr) (r int32) {
	var colUsed, m TBitmask
	var iCol Tu16
	var j, nChng, nCol, v3 int32
	var pList, pSub, pTab, pX, pY uintptr
	var v5 uint64
	_, _, _, _, _, _, _, _, _, _, _, _, _ = colUsed, iCol, j, m, nChng, nCol, pList, pSub, pTab, pX, pY, v3, v5 /* Column number */
	nChng = 0                                                                                                   /* Columns that may not be NULLed out */
	if int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x10>>4) != 0 || int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x200>>9) != 0 {
		return 0
	}
	pTab = (*TSrcItem)(unsafe.Pointer(pItem)).FpSTab
	pSub = (*TSubquery)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pItem + 44)))).FpSelect
	pX = pSub
	for {
		if !(pX != 0) {
			break
		}
		if (*TSelect)(unsafe.Pointer(pX)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Distinct)|libc.Int32FromInt32(SF_Aggregate)) != uint32(0) {
			return 0
		}
		if (*TSelect)(unsafe.Pointer(pX)).FpPrior != 0 && libc.Int32FromUint8((*TSelect)(unsafe.Pointer(pX)).Fop) != int32(TK_ALL) {
			/* This optimization does not work for compound subqueries that
			 ** use UNION, INTERSECT, or EXCEPT.  Only UNION ALL is allowed. */
			return 0
		}
		if (*TSelect)(unsafe.Pointer(pX)).FpWin != 0 {
			/* This optimization does not work for subqueries that use window
			 ** functions. */
			return 0
		}
		goto _1
	_1:
		;
		pX = (*TSelect)(unsafe.Pointer(pX)).FpPrior
	}
	colUsed = (*TSrcItem)(unsafe.Pointer(pItem)).FcolUsed
	if (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy != 0 {
		pList = (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy
		j = 0
		for {
			if !(j < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
				break
			}
			iCol = *(*Tu16)(unsafe.Pointer(pList + 8 + uintptr(j)*20 + 16))
			if libc.Int32FromUint16(iCol) > 0 {
				iCol = iCol - 1
				if libc.Int32FromUint16(iCol) >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) {
					v3 = libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) - libc.Int32FromInt32(1)
				} else {
					v3 = libc.Int32FromUint16(iCol)
				}
				colUsed = colUsed | libc.Uint64FromInt32(1)<<v3
			}
			goto _2
		_2:
			;
			j = j + 1
		}
	}
	nCol = int32((*TTable)(unsafe.Pointer(pTab)).FnCol)
	j = 0
	for {
		if !(j < nCol) {
			break
		}
		if j < libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8))-libc.Int32FromInt32(1) {
			v5 = libc.Uint64FromInt32(1) << j
		} else {
			v5 = libc.Uint64FromInt32(1) << (libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) - libc.Int32FromInt32(1))
		}
		m = v5
		if m&colUsed != uint64(0) {
			goto _4
		}
		pX = pSub
		for {
			if !(pX != 0) {
				break
			}
			pY = (*(*TExprList_item)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pX)).FpEList + 8 + uintptr(j)*20))).FpExpr
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pY)).Fop) == int32(TK_NULL) {
				goto _6
			}
			(*TExpr)(unsafe.Pointer(pY)).Fop = uint8(TK_NULL)
			**(**Tu32)(__ccgo_up(pY + 4)) &= ^libc.Uint32FromInt32(libc.Int32FromInt32(EP_Skip) | libc.Int32FromInt32(EP_Unlikely))
			**(**Tu32)(__ccgo_up(pX + 4)) |= uint32(SF_PushDown)
			nChng = nChng + 1
			goto _6
		_6:
			;
			pX = (*TSelect)(unsafe.Pointer(pX)).FpPrior
		}
		goto _4
	_4:
		;
		j = j + 1
	}
	return nChng
}

// C documentation
//
//	/*
//	** Remove the i-th cell from pPage.  This routine effects pPage only.
//	** The cell content is not freed or deallocated.  It is assumed that
//	** the cell content has been copied someplace else.  This routine just
//	** removes the reference to the cell from pPage.
//	**
//	** "sz" must be the number of bytes in the cell.
//	*/
func _dropCell(tls *libc.TLS, pPage uintptr, idx int32, sz int32, pRC uintptr) {
	var data, ptr uintptr
	var hdr, rc int32
	var pc Tu32
	_, _, _, _, _ = data, hdr, pc, ptr, rc /* Beginning of the header.  0 most pages.  100 page 1 */
	if **(**int32)(__ccgo_up(pRC)) != 0 {
		return
	}
	data = (*TMemPage)(unsafe.Pointer(pPage)).FaData
	ptr = (*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*idx)
	pc = libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(ptr)))<<libc.Int32FromInt32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(ptr + 1))))
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)
	if pc+libc.Uint32FromInt32(sz) > (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize {
		**(**int32)(__ccgo_up(pRC)) = _sqlite3CorruptError(tls, int32(80515))
		return
	}
	rc = _freeSpace(tls, pPage, libc.Int32FromUint32(pc), sz)
	if rc != 0 {
		**(**int32)(__ccgo_up(pRC)) = rc
		return
	}
	(*TMemPage)(unsafe.Pointer(pPage)).FnCell = (*TMemPage)(unsafe.Pointer(pPage)).FnCell - 1
	if libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) == 0 {
		libc.Xmemset(tls, data+uintptr(hdr+int32(1)), 0, uint32(4))
		**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(7)))) = uint8(0)
		**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)))) = uint8((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(5)) + 1)) = uint8((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize)
		(*TMemPage)(unsafe.Pointer(pPage)).FnFree = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize - uint32((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset) - uint32((*TMemPage)(unsafe.Pointer(pPage)).FchildPtrSize) - uint32(8))
	} else {
		libc.Xmemmove(tls, ptr, ptr+uintptr(2), libc.Uint32FromInt32(int32(2)*(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)-idx)))
		**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(3)))) = libc.Uint8FromInt32(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(data + uintptr(hdr+int32(3)) + 1)) = uint8((*TMemPage)(unsafe.Pointer(pPage)).FnCell)
		**(**int32)(__ccgo_up(pPage + 20)) += int32(2)
	}
}

// C documentation
//
//	/*
//	** This function returns the space in bytes required to store the copy
//	** of the Expr structure and a copy of the Expr.u.zToken string (if that
//	** string is defined.)
//	*/
func _dupedExprNodeSize(tls *libc.TLS, p uintptr, flags int32) (r int32) {
	var nByte int32
	_ = nByte
	nByte = _dupedExprStructSize(tls, p, flags) & int32(0xfff)
	if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_IntValue)) != libc.Uint32FromInt32(0)) && *(*uintptr)(unsafe.Pointer(p + 8)) != 0 {
		nByte = libc.Int32FromUint32(uint32(nByte) + (libc.Xstrlen(tls, *(*uintptr)(unsafe.Pointer(p + 8)))&libc.Uint32FromInt32(0x3fffffff) + libc.Uint32FromInt32(1)))
	}
	return (nByte + int32(7)) & ^libc.Int32FromInt32(7)
}

// C documentation
//
//	/*
//	** The dupedExpr*Size() routines each return the number of bytes required
//	** to store a copy of an expression or expression tree.  They differ in
//	** how much of the tree is measured.
//	**
//	**     dupedExprStructSize()     Size of only the Expr structure
//	**     dupedExprNodeSize()       Size of Expr + space for token
//	**     dupedExprSize()           Expr + token + subtree components
//	**
//	***************************************************************************
//	**
//	** The dupedExprStructSize() function returns two values OR-ed together:
//	** (1) the space required for a copy of the Expr structure only and
//	** (2) the EP_xxx flags that indicate what the structure size should be.
//	** The return values is always one of:
//	**
//	**      EXPR_FULLSIZE
//	**      EXPR_REDUCEDSIZE   | EP_Reduced
//	**      EXPR_TOKENONLYSIZE | EP_TokenOnly
//	**
//	** The size of the structure can be found by masking the return value
//	** of this routine with 0xfff.  The flags can be found by masking the
//	** return value with EP_Reduced|EP_TokenOnly.
//	**
//	** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
//	** (unreduced) Expr objects as they or originally constructed by the parser.
//	** During expression analysis, extra information is computed and moved into
//	** later parts of the Expr object and that extra information might get chopped
//	** off if the expression is reduced.  Note also that it does not work to
//	** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
//	** to reduce a pristine expression tree from the parser.  The implementation
//	** of dupedExprStructSize() contain multiple assert() statements that attempt
//	** to enforce this constraint.
//	*/
func _dupedExprStructSize(tls *libc.TLS, p uintptr, flags int32) (r int32) {
	var nSize int32
	_ = nSize
	/* Only one flag value allowed */
	if 0 == flags || (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_FullSize)) != uint32(0) {
		nSize = int32(52)
	} else {
		if (*TExpr)(unsafe.Pointer(p)).FpLeft != 0 || *(*uintptr)(unsafe.Pointer(p + 20)) != 0 {
			nSize = libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0)+28) | libc.Uint32FromInt32(EP_Reduced))
		} else {
			nSize = libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0)+12) | libc.Uint32FromInt32(EP_TokenOnly))
		}
	}
	return nSize
}

// C documentation
//
//	/*
//	** pCArray contains pointers to and sizes of all cells in the page being
//	** balanced.  The current page, pPg, has pPg->nCell cells starting with
//	** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
//	** starting at apCell[iNew].
//	**
//	** This routine makes the necessary adjustments to pPg so that it contains
//	** the correct cells after being balanced.
//	**
//	** The pPg->nFree field is invalid when this function returns. It is the
//	** responsibility of the caller to set it correctly.
//	*/
func _editPage(tls *libc.TLS, pPg uintptr, iOld int32, iNew int32, nNew int32, pCArray uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aData, pBegin, pCellptr uintptr
	var hdr, i, iCell, iNewEnd, iOldEnd, nAdd, nCell, nShift, nTail, v1 int32
	var _ /* pData at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _ = aData, hdr, i, iCell, iNewEnd, iOldEnd, nAdd, nCell, nShift, nTail, pBegin, pCellptr, v1
	aData = (*TMemPage)(unsafe.Pointer(pPg)).FaData
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FhdrOffset)
	pBegin = (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx + uintptr(nNew*int32(2))
	nCell = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPg)).FnCell)
	iOldEnd = iOld + libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPg)).FnCell) + libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FnOverflow)
	iNewEnd = iNew + nNew
	/* Remove cells from the start and end of the page */
	if iOld < iNew {
		nShift = _pageFreeArray(tls, pPg, iOld, iNew-iOld, pCArray)
		if nShift > nCell {
			return _sqlite3CorruptError(tls, int32(81125))
		}
		libc.Xmemmove(tls, (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx, (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx+uintptr(nShift*int32(2)), libc.Uint32FromInt32(nCell*int32(2)))
		nCell = nCell - nShift
	}
	if iNewEnd < iOldEnd {
		nTail = _pageFreeArray(tls, pPg, iNewEnd, iOldEnd-iNewEnd, pCArray)
		nCell = nCell - nTail
	}
	**(**uintptr)(__ccgo_up(bp)) = aData + uintptr(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)) + 1))))
	if **(**uintptr)(__ccgo_up(bp)) < pBegin {
		goto editpage_fail
	}
	if **(**uintptr)(__ccgo_up(bp)) > (*TMemPage)(unsafe.Pointer(pPg)).FaDataEnd {
		goto editpage_fail
	}
	/* Add cells to the start of the page */
	if iNew < iOld {
		if nNew < iOld-iNew {
			v1 = nNew
		} else {
			v1 = iOld - iNew
		}
		nAdd = v1
		pCellptr = (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx
		libc.Xmemmove(tls, pCellptr+uintptr(nAdd*int32(2)), pCellptr, libc.Uint32FromInt32(nCell*int32(2)))
		if _pageInsertArray(tls, pPg, pBegin, bp, pCellptr, iNew, nAdd, pCArray) != 0 {
			goto editpage_fail
		}
		nCell = nCell + nAdd
	}
	/* Add any overflow cells */
	i = 0
	for {
		if !(i < libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FnOverflow)) {
			break
		}
		iCell = iOld + libc.Int32FromUint16(**(**Tu16)(__ccgo_up(pPg + 28 + uintptr(i)*2))) - iNew
		if iCell >= 0 && iCell < nNew {
			pCellptr = (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx + uintptr(iCell*int32(2))
			if nCell > iCell {
				libc.Xmemmove(tls, pCellptr+2, pCellptr, libc.Uint32FromInt32((nCell-iCell)*int32(2)))
			}
			nCell = nCell + 1
			_cachedCellSize(tls, pCArray, iCell+iNew)
			if _pageInsertArray(tls, pPg, pBegin, bp, pCellptr, iCell+iNew, int32(1), pCArray) != 0 {
				goto editpage_fail
			}
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	/* Append cells to the end of the page */
	pCellptr = (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx + uintptr(nCell*int32(2))
	if _pageInsertArray(tls, pPg, pBegin, bp, pCellptr, iNew+nCell, nNew-nCell, pCArray) != 0 {
		goto editpage_fail
	}
	(*TMemPage)(unsafe.Pointer(pPg)).FnCell = libc.Uint16FromInt32(nNew)
	(*TMemPage)(unsafe.Pointer(pPg)).FnOverflow = uint8(0)
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(3)))) = libc.Uint8FromInt32(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPg)).FnCell) >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(3)) + 1)) = uint8((*TMemPage)(unsafe.Pointer(pPg)).FnCell)
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)))) = libc.Uint8FromInt32((int32(**(**uintptr)(__ccgo_up(bp))) - int32(aData)) >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)) + 1)) = libc.Uint8FromInt32(int32(**(**uintptr)(__ccgo_up(bp))) - int32(aData))
	return SQLITE_OK
	goto editpage_fail
editpage_fail:
	;
	/* Unable to edit this page. Rebuild it from scratch instead. */
	if nNew < int32(1) {
		return _sqlite3CorruptError(tls, int32(81203))
	}
	_populateCellCache(tls, pCArray, iNew, nNew)
	return _rebuildPage(tls, pCArray, iNew, nNew, pPg)
}

// C documentation
//
//	/*
//	** The StrAccum "p" is not large enough to accept N new bytes of z[].
//	** So enlarge if first, then do the append.
//	**
//	** This is a helper routine to sqlite3_str_append() that does special-case
//	** work (enlarging the buffer) using tail recursion, so that the
//	** sqlite3_str_append() routine can use fast calling semantics.
//	*/
func _enlargeAndAppend(tls *libc.TLS, p uintptr, z uintptr, N int32) {
	N = _sqlite3StrAccumEnlarge(tls, p, int64(N))
	if N > 0 {
		libc.Xmemcpy(tls, (*TStrAccum)(unsafe.Pointer(p)).FzText+uintptr((*TStrAccum)(unsafe.Pointer(p)).FnChar), z, libc.Uint32FromInt32(N))
		**(**Tu32)(__ccgo_up(p + 16)) += libc.Uint32FromInt32(N)
	}
}

// C documentation
//
//	/*
//	** Estimate the average size of a row for an index.
//	*/
func _estimateIndexWidth(tls *libc.TLS, pIdx uintptr) {
	var aCol uintptr
	var i, v2 int32
	var wIndex uint32
	var x Ti16
	_, _, _, _, _ = aCol, i, wIndex, x, v2
	wIndex = uint32(0)
	aCol = (*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FaCol
	i = 0
	for {
		if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)) {
			break
		}
		x = **(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2))
		if int32(x) < 0 {
			v2 = int32(1)
		} else {
			v2 = libc.Int32FromUint8((**(**TColumn)(__ccgo_up(aCol + uintptr(x)*12))).FszEst)
		}
		wIndex = wIndex + libc.Uint32FromInt32(v2)
		goto _1
	_1:
		;
		i = i + 1
	}
	(*TIndex)(unsafe.Pointer(pIdx)).FszIdxRow = _sqlite3LogEst(tls, uint64(wIndex*uint32(4)))
}

// C documentation
//
//	/*
//	** Argument pWhere is the WHERE clause belonging to SELECT statement p. This
//	** function attempts to transform expressions of the form:
//	**
//	**     EXISTS (SELECT ...)
//	**
//	** into joins. For example, given
//	**
//	**    CREATE TABLE sailors(sid INTEGER PRIMARY KEY, name TEXT);
//	**    CREATE TABLE reserves(sid INT, day DATE, PRIMARY KEY(sid, day));
//	**
//	**    SELECT name FROM sailors AS S WHERE EXISTS (
//	**      SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25'
//	**    );
//	**
//	** the SELECT statement may be transformed as follows:
//	**
//	**    SELECT name FROM sailors AS S, reserves AS R
//	**      WHERE S.sid = R.sid AND R.day = '2022-10-25';
//	**
//	** **Approximately**.  Really, we have to ensure that the FROM-clause term
//	** that was formerly inside the EXISTS is only executed once.  This is handled
//	** by setting the SrcItem.fg.fromExists flag, which then causes code in
//	** the where.c file to exit the corresponding loop after the first successful
//	** match (if any).
//	*/
func _existsToJoin(tls *libc.TLS, pParse uintptr, p uintptr, pWhere uintptr) {
	var aCsrMap, db, pRight, pSub, pSubWhere uintptr
	_, _, _, _, _ = aCsrMap, db, pRight, pSub, pSubWhere
	if (*TParse)(unsafe.Pointer(pParse)).FnErr == 0 && pWhere != uintptr(0) && !((*TExpr)(unsafe.Pointer(pWhere)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON)) != libc.Uint32FromInt32(0)) && (*TSelect)(unsafe.Pointer(p)).FpSrc != uintptr(0) && (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc)).FnSrc < libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) && ((*TSelect)(unsafe.Pointer(p)).FpLimit == uintptr(0) || (*TExpr)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpLimit)).FpRight == uintptr(0)) {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pWhere)).Fop) == int32(TK_AND) {
			pRight = (*TExpr)(unsafe.Pointer(pWhere)).FpRight
			_existsToJoin(tls, pParse, p, (*TExpr)(unsafe.Pointer(pWhere)).FpLeft)
			_existsToJoin(tls, pParse, p, pRight)
		} else {
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pWhere)).Fop) == int32(TK_EXISTS) {
				pSub = *(*uintptr)(unsafe.Pointer(pWhere + 20))
				pSubWhere = (*TSelect)(unsafe.Pointer(pSub)).FpWhere
				if (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSub)).FpSrc)).FnSrc == int32(1) && (*TSelect)(unsafe.Pointer(pSub)).FselFlags&uint32(SF_Aggregate) == uint32(0) && !(int32(*(*uint32)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSub)).FpSrc + 8 + 12 + 4))&0x4>>2) != 0) && (*TSelect)(unsafe.Pointer(pSub)).FpLimit == uintptr(0) && (*TSelect)(unsafe.Pointer(pSub)).FpPrior == uintptr(0) {
					/* Before combining the sub-select with the parent, renumber the
					 ** cursor used by the subselect. This is because the EXISTS expression
					 ** might be a copy of another EXISTS expression from somewhere
					 ** else in the tree, and in this case it is important that it use
					 ** a unique cursor number.  */
					db = (*TParse)(unsafe.Pointer(pParse)).Fdb
					aCsrMap = _sqlite3DbMallocZero(tls, db, uint64(libc.Uint32FromInt32((*TParse)(unsafe.Pointer(pParse)).FnTab+libc.Int32FromInt32(2))*uint32(4)))
					if aCsrMap == uintptr(0) {
						return
					}
					**(**int32)(__ccgo_up(aCsrMap)) = (*TParse)(unsafe.Pointer(pParse)).FnTab + int32(1)
					_renumberCursors(tls, pParse, pSub, -int32(1), aCsrMap)
					_sqlite3DbFree(tls, db, aCsrMap)
					libc.Xmemset(tls, pWhere, 0, uint32(52))
					(*TExpr)(unsafe.Pointer(pWhere)).Fop = uint8(TK_INTEGER)
					*(*int32)(unsafe.Pointer(pWhere + 8)) = int32(1)
					**(**Tu32)(__ccgo_up(pWhere + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_IntValue))
					libc.SetBitFieldPtr32Uint32((*TSelect)(unsafe.Pointer(pSub)).FpSrc+8+12+4, libc.Uint32FromInt32(1), 18, 0x40000)
					(*TSelect)(unsafe.Pointer(p)).FpSrc = _sqlite3SrcListAppendList(tls, pParse, (*TSelect)(unsafe.Pointer(p)).FpSrc, (*TSelect)(unsafe.Pointer(pSub)).FpSrc)
					if pSubWhere != 0 {
						(*TSelect)(unsafe.Pointer(p)).FpWhere = _sqlite3PExpr(tls, pParse, int32(TK_AND), (*TSelect)(unsafe.Pointer(p)).FpWhere, pSubWhere)
						(*TSelect)(unsafe.Pointer(pSub)).FpWhere = uintptr(0)
					}
					(*TSelect)(unsafe.Pointer(pSub)).FpSrc = uintptr(0)
					_sqlite3ParserAddCleanup(tls, pParse, __ccgo_fp(_sqlite3SelectDeleteGeneric), pSub)
				}
			}
		}
	}
}

// C documentation
//
//	/*
//	** Generate code for a BETWEEN operator.
//	**
//	**    x BETWEEN y AND z
//	**
//	** The above is equivalent to
//	**
//	**    x>=y AND x<=z
//	**
//	** Code it as such, taking care to do the common subexpression
//	** elimination of x.
//	**
//	** The xJumpIf parameter determines details:
//	**
//	**    NULL:                   Store the boolean result in reg[dest]
//	**    sqlite3ExprIfTrue:      Jump to dest if true
//	**    sqlite3ExprIfFalse:     Jump to dest if false
//	**
//	** The jumpIfNull parameter is ignored if xJumpIf is NULL.
//	*/
func _exprCodeBetween(tls *libc.TLS, pParse uintptr, pExpr uintptr, dest int32, __ccgo_fp_xJump uintptr, jumpIfNull int32) {
	bp := tls.Alloc(160)
	defer tls.Free(160)
	var db, pDel uintptr
	var _ /* compLeft at bp+52 */ TExpr
	var _ /* compRight at bp+104 */ TExpr
	var _ /* exprAnd at bp+0 */ TExpr
	var _ /* regFree1 at bp+156 */ int32
	_, _ = db, pDel                      /* The  x<=z  term */
	**(**int32)(__ccgo_up(bp + 156)) = 0 /* Temporary use register */
	pDel = uintptr(0)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	libc.Xmemset(tls, bp+52, 0, uint32(52))
	libc.Xmemset(tls, bp+104, 0, uint32(52))
	libc.Xmemset(tls, bp, 0, uint32(52))
	pDel = _sqlite3ExprDup(tls, db, (*TExpr)(unsafe.Pointer(pExpr)).FpLeft, 0)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
		(**(**TExpr)(__ccgo_up(bp))).Fop = uint8(TK_AND)
		(**(**TExpr)(__ccgo_up(bp))).FpLeft = bp + 52
		(**(**TExpr)(__ccgo_up(bp))).FpRight = bp + 104
		(**(**TExpr)(__ccgo_up(bp + 52))).Fop = uint8(TK_GE)
		(**(**TExpr)(__ccgo_up(bp + 52))).FpLeft = pDel
		(**(**TExpr)(__ccgo_up(bp + 52))).FpRight = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8))).FpExpr
		(**(**TExpr)(__ccgo_up(bp + 104))).Fop = uint8(TK_LE)
		(**(**TExpr)(__ccgo_up(bp + 104))).FpLeft = pDel
		(**(**TExpr)(__ccgo_up(bp + 104))).FpRight = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8 + 1*20))).FpExpr
		_sqlite3ExprToRegister(tls, pDel, _exprCodeVector(tls, pParse, pDel, bp+156))
		if __ccgo_fp_xJump != 0 {
			(*(*func(*libc.TLS, uintptr, uintptr, int32, int32))(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xJump})))(tls, pParse, bp, dest, jumpIfNull)
		} else {
			/* Mark the expression is being from the ON or USING clause of a join
			 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
			 ** it into the Parse.pConstExpr list.  We should use a new bit for this,
			 ** for clarity, but we are out of bits in the Expr.flags field so we
			 ** have to reuse the EP_OuterON bit.  Bummer. */
			**(**Tu32)(__ccgo_up(pDel + 4)) |= uint32(EP_OuterON)
			_sqlite3ExprCodeTarget(tls, pParse, bp, dest)
		}
		_sqlite3ReleaseTempReg(tls, pParse, **(**int32)(__ccgo_up(bp + 156)))
	}
	_sqlite3ExprDelete(tls, db, pDel)
	/* Ensure adequate test coverage */
}

// C documentation
//
//	/*
//	** Evaluate an expression (either a vector or a scalar expression) and store
//	** the result in contiguous temporary registers.  Return the index of
//	** the first register used to store the result.
//	**
//	** If the returned result register is a temporary scalar, then also write
//	** that register number into *piFreeable.  If the returned result register
//	** is not a temporary or if the expression is a vector set *piFreeable
//	** to 0.
//	*/
func _exprCodeVector(tls *libc.TLS, pParse uintptr, p uintptr, piFreeable uintptr) (r int32) {
	var i, iResult, nResult int32
	_, _, _ = i, iResult, nResult
	nResult = _sqlite3ExprVectorSize(tls, p)
	if nResult == int32(1) {
		iResult = _sqlite3ExprCodeTemp(tls, pParse, p, piFreeable)
	} else {
		**(**int32)(__ccgo_up(piFreeable)) = 0
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_SELECT) {
			iResult = _sqlite3CodeSubselect(tls, pParse, p)
		} else {
			iResult = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
			**(**int32)(__ccgo_up(pParse + 48)) += nResult
			i = 0
			for {
				if !(i < nResult) {
					break
				}
				_sqlite3ExprCodeFactorable(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(p + 20)) + 8 + uintptr(i)*20))).FpExpr, i+iResult)
				goto _1
			_1:
				;
				i = i + 1
			}
		}
	}
	return iResult
}

// C documentation
//
//	/* This walker callback will compute the union of colFlags flags for all
//	** referenced columns in a CHECK constraint or generated column expression.
//	*/
func _exprColumnFlagUnion(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) && int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) >= 0 {
		v1 = pWalker + 20
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pWalker + 24)))).FaCol + uintptr((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)*12))).FcolFlags))
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
//	** is not NULL then it points to memory that can be used to store a copy
//	** of the input Expr p together with its p->u.zToken (if any).  pEdupBuf
//	** is updated with the new buffer tail prior to returning.
//	*/
func _exprDup(tls *libc.TLS, db uintptr, p uintptr, dupFlags int32, pEdupBuf uintptr) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nAlloc, nNewSize, nToken, v2 int32
	var nSize, staticFlag Tu32
	var nStructSize uint32
	var pNew, zToken, v1 uintptr
	var _ /* sEdupBuf at bp+0 */ TEdupBuf
	_, _, _, _, _, _, _, _, _, _ = nAlloc, nNewSize, nSize, nStructSize, nToken, pNew, staticFlag, zToken, v1, v2 /* EP_Static if space not obtained from malloc */
	nToken = -int32(1)                                                                                            /* Space needed for p->u.zToken.  -1 means unknown */
	/* Figure out where to write the new Expr structure. */
	if pEdupBuf != 0 {
		(**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc = (*TEdupBuf)(unsafe.Pointer(pEdupBuf)).FzAlloc
		staticFlag = uint32(EP_Static)
	} else {
		if dupFlags != 0 {
			nAlloc = _dupedExprSize(tls, p)
		} else {
			if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_IntValue)) != libc.Uint32FromInt32(0)) && *(*uintptr)(unsafe.Pointer(p + 8)) != 0 {
				nToken = libc.Int32FromUint32(libc.Xstrlen(tls, *(*uintptr)(unsafe.Pointer(p + 8)))&uint32(0x3fffffff) + uint32(1))
				nAlloc = libc.Int32FromUint32((libc.Uint32FromInt64(52) + libc.Uint32FromInt32(nToken) + libc.Uint32FromInt32(7)) & libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
			} else {
				nToken = 0
				nAlloc = libc.Int32FromUint32((libc.Uint32FromInt64(52) + libc.Uint32FromInt32(7)) & libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
			}
		}
		(**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc = _sqlite3DbMallocRawNN(tls, db, libc.Uint64FromInt32(nAlloc))
		staticFlag = uint32(0)
	}
	pNew = (**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc
	if pNew != 0 {
		/* Set nNewSize to the size allocated for the structure pointed to
		 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
		 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
		 ** by the copy of the p->u.zToken string (if any).
		 */
		nStructSize = libc.Uint32FromInt32(_dupedExprStructSize(tls, p, dupFlags))
		nNewSize = libc.Int32FromUint32(nStructSize & uint32(0xfff))
		if nToken < 0 {
			if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_IntValue)) != libc.Uint32FromInt32(0)) && *(*uintptr)(unsafe.Pointer(p + 8)) != 0 {
				nToken = _sqlite3Strlen30(tls, *(*uintptr)(unsafe.Pointer(p + 8))) + int32(1)
			} else {
				nToken = 0
			}
		}
		if dupFlags != 0 {
			libc.Xmemcpy(tls, (**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc, p, libc.Uint32FromInt32(nNewSize))
		} else {
			nSize = libc.Uint32FromInt32(_exprStructSize(tls, p))
			libc.Xmemcpy(tls, (**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc, p, nSize)
			if nSize < uint32(52) {
				libc.Xmemset(tls, (**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc+uintptr(nSize), 0, uint32(52)-nSize)
			}
			nNewSize = int32(52)
		}
		/* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
		**(**Tu32)(__ccgo_up(pNew + 4)) &= libc.Uint32FromInt32(^(libc.Int32FromInt32(EP_Reduced) | libc.Int32FromInt32(EP_TokenOnly) | libc.Int32FromInt32(EP_Static)))
		**(**Tu32)(__ccgo_up(pNew + 4)) |= nStructSize & libc.Uint32FromInt32(libc.Int32FromInt32(EP_Reduced)|libc.Int32FromInt32(EP_TokenOnly))
		**(**Tu32)(__ccgo_up(pNew + 4)) |= staticFlag
		if dupFlags != 0 {
		}
		/* Copy the p->u.zToken string, if any. */
		if nToken > 0 {
			v1 = (**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc + uintptr(nNewSize)
			*(*uintptr)(unsafe.Pointer(pNew + 8)) = v1
			zToken = v1
			libc.Xmemcpy(tls, zToken, *(*uintptr)(unsafe.Pointer(p + 8)), libc.Uint32FromInt32(nToken))
			nNewSize = nNewSize + nToken
		}
		(**(**TEdupBuf)(__ccgo_up(bp))).FzAlloc += uintptr((nNewSize + libc.Int32FromInt32(7)) & ^libc.Int32FromInt32(7))
		if ((*TExpr)(unsafe.Pointer(p)).Fflags|(*TExpr)(unsafe.Pointer(pNew)).Fflags)&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)|libc.Int32FromInt32(EP_Leaf)) == uint32(0) {
			/* Fill in the pNew->x.pSelect or pNew->x.pList member. */
			if (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
				*(*uintptr)(unsafe.Pointer(pNew + 20)) = _sqlite3SelectDup(tls, db, *(*uintptr)(unsafe.Pointer(p + 20)), dupFlags)
			} else {
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) != int32(TK_ORDER) {
					v2 = dupFlags
				} else {
					v2 = 0
				}
				*(*uintptr)(unsafe.Pointer(pNew + 20)) = _sqlite3ExprListDup(tls, db, *(*uintptr)(unsafe.Pointer(p + 20)), v2)
			}
			if (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
				*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pNew)).Fy)) = _sqlite3WindowDup(tls, db, pNew, *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(p)).Fy)))
			}
			/* Fill in pNew->pLeft and pNew->pRight. */
			if dupFlags != 0 {
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_SELECT_COLUMN) {
					(*TExpr)(unsafe.Pointer(pNew)).FpLeft = (*TExpr)(unsafe.Pointer(p)).FpLeft
				} else {
					if (*TExpr)(unsafe.Pointer(p)).FpLeft != 0 {
						v1 = _exprDup(tls, db, (*TExpr)(unsafe.Pointer(p)).FpLeft, int32(EXPRDUP_REDUCE), bp)
					} else {
						v1 = uintptr(0)
					}
					(*TExpr)(unsafe.Pointer(pNew)).FpLeft = v1
				}
				if (*TExpr)(unsafe.Pointer(p)).FpRight != 0 {
					v1 = _exprDup(tls, db, (*TExpr)(unsafe.Pointer(p)).FpRight, int32(EXPRDUP_REDUCE), bp)
				} else {
					v1 = uintptr(0)
				}
				(*TExpr)(unsafe.Pointer(pNew)).FpRight = v1
			} else {
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_SELECT_COLUMN) {
					(*TExpr)(unsafe.Pointer(pNew)).FpLeft = (*TExpr)(unsafe.Pointer(p)).FpLeft
				} else {
					(*TExpr)(unsafe.Pointer(pNew)).FpLeft = _sqlite3ExprDup(tls, db, (*TExpr)(unsafe.Pointer(p)).FpLeft, 0)
				}
				(*TExpr)(unsafe.Pointer(pNew)).FpRight = _sqlite3ExprDup(tls, db, (*TExpr)(unsafe.Pointer(p)).FpRight, 0)
			}
		}
	}
	if pEdupBuf != 0 {
		libc.Xmemcpy(tls, pEdupBuf, bp, uint32(4))
	}
	return pNew
}

// C documentation
//
//	/*
//	** Check to see if there are references to columns in table
//	** pWalker->u.pIdxCover->iCur can be satisfied using the index
//	** pWalker->u.pIdxCover->pIdx.
//	*/
func _exprIdxCover(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(pExpr)).FiTable == (*TIdxCover)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pWalker + 24)))).FiCur && _sqlite3TableColumnToIndex(tls, (*TIdxCover)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pWalker + 24)))).FpIdx, int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)) < 0 {
		(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(1)
		return int32(WRC_Abort)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Return non-zero if Expr p can only be true if pNN is not NULL.
//	**
//	** Or if seenNot is true, return non-zero if Expr p can only be
//	** non-NULL if pNN is not NULL
//	*/
func _exprImpliesNotNull(tls *libc.TLS, pParse uintptr, p uintptr, pNN uintptr, iTab int32, seenNot int32) (r int32) {
	var pList uintptr
	_ = pList
	if _sqlite3ExprCompare(tls, pParse, p, pNN, iTab) == 0 {
		return libc.BoolInt32(libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pNN)).Fop) != int32(TK_NULL))
	}
	switch libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) {
	case int32(TK_IN):
		if seenNot != 0 && (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_xIsSelect)) != uint32(0) {
			return 0
		}
		return _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpLeft, pNN, iTab, int32(1))
	case int32(TK_BETWEEN):
		pList = *(*uintptr)(unsafe.Pointer(p + 20))
		if seenNot != 0 {
			return 0
		}
		if _exprImpliesNotNull(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pList + 8))).FpExpr, pNN, iTab, int32(1)) != 0 || _exprImpliesNotNull(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + 1*20))).FpExpr, pNN, iTab, int32(1)) != 0 {
			return int32(1)
		}
		return _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpLeft, pNN, iTab, int32(1))
	case int32(TK_EQ):
		fallthrough
	case int32(TK_NE):
		fallthrough
	case int32(TK_LT):
		fallthrough
	case int32(TK_LE):
		fallthrough
	case int32(TK_GT):
		fallthrough
	case int32(TK_GE):
		fallthrough
	case int32(TK_PLUS):
		fallthrough
	case int32(TK_MINUS):
		fallthrough
	case int32(TK_BITOR):
		fallthrough
	case int32(TK_LSHIFT):
		fallthrough
	case int32(TK_RSHIFT):
		fallthrough
	case int32(TK_CONCAT):
		seenNot = int32(1)
		fallthrough
	case int32(TK_STAR):
		fallthrough
	case int32(TK_REM):
		fallthrough
	case int32(TK_BITAND):
		fallthrough
	case int32(TK_SLASH):
		if _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpRight, pNN, iTab, seenNot) != 0 {
			return int32(1)
		}
		fallthrough
	case int32(TK_SPAN):
		fallthrough
	case int32(TK_COLLATE):
		fallthrough
	case int32(TK_UPLUS):
		fallthrough
	case int32(TK_UMINUS):
		return _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpLeft, pNN, iTab, seenNot)
	case int32(TK_TRUTH):
		if seenNot != 0 {
			return 0
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop2) != int32(TK_IS) {
			return 0
		}
		return _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpLeft, pNN, iTab, int32(1))
	case int32(TK_BITNOT):
		fallthrough
	case int32(TK_NOT):
		return _exprImpliesNotNull(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FpLeft, pNN, iTab, int32(1))
	}
	return 0
}

func _exprIsConst(tls *libc.TLS, pParse uintptr, p uintptr, initFlag int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	(**(**TWalker)(__ccgo_up(bp))).FeCode = libc.Uint16FromInt32(initFlag)
	(**(**TWalker)(__ccgo_up(bp))).FpParse = pParse
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_exprNodeIsConstant)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_sqlite3SelectWalkFail)
	_sqlite3WalkExpr(tls, bp, p)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

// C documentation
//
//	/*
//	** pIdx is an index containing expressions.  Check it see if any of the
//	** expressions in the index match the pExpr expression.
//	*/
func _exprIsCoveredByIndex(tls *libc.TLS, pExpr uintptr, pIdx uintptr, iTabCur int32) (r int32) {
	var i int32
	_ = i
	i = 0
	for {
		if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)) {
			break
		}
		if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2))) == -int32(2) && _sqlite3ExprCompare(tls, uintptr(0), pExpr, (*(*TExprList_item)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FaColExpr + 8 + uintptr(i)*20))).FpExpr, iTabCur) == 0 {
			return int32(1)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** Return true if the expression contains no non-deterministic SQL
//	** functions. Do not consider non-deterministic SQL functions that are
//	** part of sub-select statements.
//	*/
func _exprIsDeterministic(tls *libc.TLS, p uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	libc.Xmemset(tls, bp, 0, uint32(28))
	(**(**TWalker)(__ccgo_up(bp))).FeCode = uint16(1)
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_exprNodeIsDeterministic)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_sqlite3SelectWalkFail)
	_sqlite3WalkExpr(tls, bp, p)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

// C documentation
//
//	/*
//	** Append a copy of each expression in expression-list pAppend to
//	** expression list pList. Return a pointer to the result list.
//	*/
func _exprListAppendList(tls *libc.TLS, pParse uintptr, pList uintptr, pAppend uintptr, bIntToNull int32) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, pDup, pSub uintptr
	var i, nInit, v1 int32
	var _ /* iDummy at bp+0 */ int32
	_, _, _, _, _, _ = db, i, nInit, pDup, pSub, v1
	if pAppend != 0 {
		if pList != 0 {
			v1 = (*TExprList)(unsafe.Pointer(pList)).FnExpr
		} else {
			v1 = 0
		}
		nInit = v1
		i = 0
		for {
			if !(i < (*TExprList)(unsafe.Pointer(pAppend)).FnExpr) {
				break
			}
			db = (*TParse)(unsafe.Pointer(pParse)).Fdb
			pDup = _sqlite3ExprDup(tls, db, (*(*TExprList_item)(unsafe.Pointer(pAppend + 8 + uintptr(i)*20))).FpExpr, 0)
			if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
				_sqlite3ExprDelete(tls, db, pDup)
				break
			}
			if bIntToNull != 0 {
				pSub = _sqlite3ExprSkipCollateAndLikely(tls, pDup)
				if _sqlite3ExprIsInteger(tls, pSub, bp, uintptr(0)) != 0 {
					(*TExpr)(unsafe.Pointer(pSub)).Fop = uint8(TK_NULL)
					**(**Tu32)(__ccgo_up(pSub + 4)) &= libc.Uint32FromInt32(^(libc.Int32FromInt32(EP_IntValue) | libc.Int32FromInt32(EP_IsTrue) | libc.Int32FromInt32(EP_IsFalse)))
					*(*uintptr)(unsafe.Pointer(pSub + 8)) = uintptr(0)
				}
			}
			pList = _sqlite3ExprListAppend(tls, pParse, pList, pDup)
			if pList != 0 {
				(*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(nInit+i)*20))).Ffg.FsortFlags = (*(*TExprList_item)(unsafe.Pointer(pAppend + 8 + uintptr(i)*20))).Ffg.FsortFlags
			}
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	return pList
}

func _exprMightBeIndexed(tls *libc.TLS, pFrom uintptr, aiCurCol uintptr, pExpr uintptr, op int32) (r int32) {
	var i int32
	var pIdx uintptr
	_, _ = i, pIdx
	/* If this expression is a vector to the left or right of a
	 ** inequality constraint (>, <, >= or <=), perform the processing
	 ** on the first element of the vector.  */
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_VECTOR) && (op >= int32(TK_GT) && op <= int32(TK_GE)) {
		pExpr = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8))).FpExpr
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) {
		**(**int32)(__ccgo_up(aiCurCol)) = (*TExpr)(unsafe.Pointer(pExpr)).FiTable
		**(**int32)(__ccgo_up(aiCurCol + 1*4)) = int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)
		return int32(1)
	}
	i = 0
	for {
		if !(i < (*TSrcList)(unsafe.Pointer(pFrom)).FnSrc) {
			break
		}
		pIdx = (*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer(pFrom + 8 + uintptr(i)*48))).FpSTab)).FpIndex
		for {
			if !(pIdx != 0) {
				break
			}
			if (*TIndex)(unsafe.Pointer(pIdx)).FaColExpr != 0 {
				return _exprMightBeIndexed2(tls, pFrom, aiCurCol, pExpr, i)
			}
			goto _2
		_2:
			;
			pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** Expression pExpr is one operand of a comparison operator that might
//	** be useful for indexing.  This routine checks to see if pExpr appears
//	** in any index.  Return TRUE (1) if pExpr is an indexed term and return
//	** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
//	** number of the table that is indexed and aiCurCol[1] to the column number
//	** of the column that is indexed, or XN_EXPR (-2) if an expression is being
//	** indexed.
//	**
//	** If pExpr is a TK_COLUMN column reference, then this routine always returns
//	** true even if that particular column is not indexed, because the column
//	** might be added to an automatic index later.
//	*/
func _exprMightBeIndexed2(tls *libc.TLS, pFrom uintptr, aiCurCol uintptr, pExpr uintptr, j int32) (r int32) {
	var i, iCur, v1 int32
	var pIdx uintptr
	_, _, _, _ = i, iCur, pIdx, v1
	for {
		iCur = (*(*TSrcItem)(unsafe.Pointer(pFrom + 8 + uintptr(j)*48))).FiCursor
		pIdx = (*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer(pFrom + 8 + uintptr(j)*48))).FpSTab)).FpIndex
		for {
			if !(pIdx != 0) {
				break
			}
			if (*TIndex)(unsafe.Pointer(pIdx)).FaColExpr == uintptr(0) {
				goto _3
			}
			i = 0
			for {
				if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)) {
					break
				}
				if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2))) != -int32(2) {
					goto _4
				}
				if _sqlite3ExprCompareSkip(tls, pExpr, (*(*TExprList_item)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FaColExpr + 8 + uintptr(i)*20))).FpExpr, iCur) == 0 && !(_sqlite3ExprIsConstant(tls, uintptr(0), (*(*TExprList_item)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FaColExpr + 8 + uintptr(i)*20))).FpExpr) != 0) {
					**(**int32)(__ccgo_up(aiCurCol)) = iCur
					**(**int32)(__ccgo_up(aiCurCol + 1*4)) = -int32(2)
					return int32(1)
				}
				goto _4
			_4:
				;
				i = i + 1
			}
			goto _3
		_3:
			;
			pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		}
		goto _2
	_2:
		;
		j = j + 1
		v1 = j
		if !(v1 < (*TSrcList)(unsafe.Pointer(pFrom)).FnSrc) {
			break
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** Expression Node callback for sqlite3ExprCanReturnSubtype().  If
//	** pExpr is able to return a subtype, set pWalker->eCode and abort
//	** the search.  If pExpr can never return a subtype, prune search.
//	**
//	** The only expressions that can return a subtype are:
//	**
//	**    1.  A function
//	**    2.  The no-op "+" operator
//	**    3.  A CASE...END expression
//	**    4.  A CAST() expression
//	**    5.  A "expr COLLATE colseq" expression.
//	**
//	** For any other kind of expression, prune the search.
//	**
//	** For case 1, the expression can yield a subtype if the function has
//	** the SQLITE_RESULT_SUBTYPE property.  Functions can also return
//	** a subtype (via sqlite3_result_value()) if any of the arguments can
//	** return a subtype.
//	**
//	** In all cases 1 through 5, the expression might also return a subtype
//	** if any operand can return a subtype.
//	*/
func _exprNodeCanReturnSubtype(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var db, pDef uintptr
	var n, v1 int32
	_, _, _, _ = db, n, pDef, v1
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_CASE) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_UPLUS) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLLATE) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_CAST) {
		return WRC_Continue
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_FUNCTION) {
		return int32(WRC_Prune)
	}
	db = (*TParse)(unsafe.Pointer((*TWalker)(unsafe.Pointer(pWalker)).FpParse)).Fdb
	if *(*uintptr)(unsafe.Pointer(pExpr + 20)) != 0 {
		v1 = (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FnExpr
	} else {
		v1 = 0
	}
	n = v1
	pDef = _sqlite3FindFunction(tls, db, *(*uintptr)(unsafe.Pointer(pExpr + 8)), n, (*Tsqlite3)(unsafe.Pointer(db)).Fenc, uint8(0))
	if pDef == uintptr(0) || (*TFuncDef)(unsafe.Pointer(pDef)).FfuncFlags&uint32(SQLITE_RESULT_SUBTYPE) != uint32(0) {
		(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(1)
		return int32(WRC_Abort)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** These routines are Walker callbacks used to check expressions to
//	** see if they are "constant" for some definition of constant.  The
//	** Walker.eCode value determines the type of "constant" we are looking
//	** for.
//	**
//	** These callback routines are used to implement the following:
//	**
//	**     sqlite3ExprIsConstant()                  pWalker->eCode==1
//	**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
//	**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
//	**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
//	**
//	** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
//	** is found to not be a constant.
//	**
//	** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
//	** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5
//	** when parsing an existing schema out of the sqlite_schema table and 4
//	** when processing a new CREATE TABLE statement.  A bound parameter raises
//	** an error for new statements, but is silently converted
//	** to NULL for existing schemas.  This allows sqlite_schema tables that
//	** contain a bound parameter because they were generated by older versions
//	** of SQLite to be parsed by newer versions of SQLite without raising a
//	** malformed schema error.
//	*/
func _exprNodeIsConstant(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	/* If pWalker->eCode is 2 then any term of the expression that comes from
	 ** the ON or USING clauses of an outer join disqualifies the expression
	 ** from being considered constant. */
	if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == int32(2) && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0) {
		(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(0)
		return int32(WRC_Abort)
	}
	switch libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) {
	/* Consider functions to be constant if all their arguments are constant
	 ** and either pWalker->eCode==4 or 5 or the function has the
	 ** SQLITE_FUNC_CONST flag. */
	case int32(TK_FUNCTION):
		if (libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) >= int32(4) || (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_ConstFunc)) != uint32(0)) && !((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != libc.Uint32FromInt32(0)) {
			if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == int32(5) {
				**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_FromDDL))
			}
			return WRC_Continue
		} else {
			if (*TWalker)(unsafe.Pointer(pWalker)).FpParse != 0 {
				return _exprNodeIsConstantFunction(tls, pWalker, pExpr)
			} else {
				(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(0)
				return int32(WRC_Abort)
			}
		}
		fallthrough
	case int32(TK_ID):
		/* Convert "true" or "false" in a DEFAULT clause into the
		 ** appropriate TK_TRUEFALSE operator */
		if _sqlite3ExprIdToTrueFalse(tls, pExpr) != 0 {
			return int32(WRC_Prune)
		}
		fallthrough
	case int32(TK_COLUMN):
		fallthrough
	case int32(TK_AGG_FUNCTION):
		fallthrough
	case int32(TK_AGG_COLUMN):
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_FixedCol)) != uint32(0) && libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) != int32(2) {
			return WRC_Continue
		}
		if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == int32(3) && (*TExpr)(unsafe.Pointer(pExpr)).FiTable == *(*int32)(unsafe.Pointer(pWalker + 24)) {
			return WRC_Continue
		}
		fallthrough
	case int32(TK_IF_NULL_ROW):
		fallthrough
	case int32(TK_REGISTER):
		fallthrough
	case int32(TK_DOT):
		fallthrough
	case int32(TK_RAISE):
		(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(0)
		return int32(WRC_Abort)
	case int32(TK_VARIABLE):
		if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == int32(5) {
			/* Silently convert bound parameters that appear inside of CREATE
			 ** statements into a NULL when parsing the CREATE statement text out
			 ** of the sqlite_schema table */
			(*TExpr)(unsafe.Pointer(pExpr)).Fop = uint8(TK_NULL)
		} else {
			if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == int32(4) {
				/* A bound parameter in a CREATE statement that originates from
				 ** sqlite3_prepare() causes an error */
				(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(0)
				return int32(WRC_Abort)
			}
		}
		fallthrough
	default:
		/* sqlite3SelectWalkFail() disallows */
		/* sqlite3SelectWalkFail() disallows */
		return WRC_Continue
	}
	return r
}

// C documentation
//
//	/*
//	** pExpr is a TK_FUNCTION node.  Try to determine whether or not the
//	** function is a constant function.  A function is constant if all of
//	** the following are true:
//	**
//	**    (1)  It is a scalar function (not an aggregate or window function)
//	**    (2)  It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG
//	**         property.
//	**    (3)  All of its arguments are constants
//	**
//	** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
//	** It makes no changes to pWalker->eCode if pExpr is constant.  In
//	** every case, it returns WRC_Abort.
//	**
//	** Called as a service subroutine from exprNodeIsConstant().
//	*/
func _exprNodeIsConstantFunction(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var db, pDef, pList, v1 uintptr
	var n int32
	var v2 bool
	_, _, _, _, _, _ = db, n, pDef, pList, v1, v2 /* The database */
	if v2 = (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)) != uint32(0); !v2 {
		v1 = *(*uintptr)(unsafe.Pointer(pExpr + 20))
		pList = v1
	}
	if v2 || v1 == uintptr(0) {
		n = 0
	} else {
		n = (*TExprList)(unsafe.Pointer(pList)).FnExpr
		_sqlite3WalkExprList(tls, pWalker, pList)
		if libc.Int32FromUint16((*TWalker)(unsafe.Pointer(pWalker)).FeCode) == 0 {
			return int32(WRC_Abort)
		}
	}
	db = (*TParse)(unsafe.Pointer((*TWalker)(unsafe.Pointer(pWalker)).FpParse)).Fdb
	pDef = _sqlite3FindFunction(tls, db, *(*uintptr)(unsafe.Pointer(pExpr + 8)), n, (*Tsqlite3)(unsafe.Pointer(db)).Fenc, uint8(0))
	if pDef == uintptr(0) || (*TFuncDef)(unsafe.Pointer(pDef)).FxFinalize != uintptr(0) || (*TFuncDef)(unsafe.Pointer(pDef)).FfuncFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_FUNC_CONSTANT)|libc.Int32FromInt32(SQLITE_FUNC_SLOCHNG)) == uint32(0) || (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
		(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(0)
		return int32(WRC_Abort)
	}
	return int32(WRC_Prune)
}

// C documentation
//
//	/*
//	** Callback for estLikePatternLength().
//	**
//	** If this node is a string literal that is longer pWalker->sz, then set
//	** pWalker->sz to the byte length of that string literal.
//	**
//	** pWalker->eCode indicates how to count characters:
//	**
//	**    eCode==0     Count as a GLOB pattern
//	**    eCode==1     Count as a LIKE pattern
//	*/
func _exprNodePatternLengthEst(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var c, c1, c2, c3, v1 Tu8
	var sz int32
	var z, v2 uintptr
	_, _, _, _, _, _, _, _ = c, c1, c2, c3, sz, z, v1, v2
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_STRING) {
		sz = 0                                     /* Pattern size in bytes */
		z = *(*uintptr)(unsafe.Pointer(pExpr + 8)) /* Wildcards */
		if (*TWalker)(unsafe.Pointer(pWalker)).FeCode != 0 {
			c1 = uint8('%')
			c2 = uint8('_')
			c3 = uint8(0)
		} else {
			c1 = uint8('*')
			c2 = uint8('?')
			c3 = uint8('[')
		}
		for {
			v2 = z
			z = z + 1
			v1 = **(**Tu8)(__ccgo_up(v2))
			c = v1
			if !(libc.Int32FromUint8(v1) != 0) {
				break
			}
			if libc.Int32FromUint8(c) == libc.Int32FromUint8(c3) {
				if **(**Tu8)(__ccgo_up(z)) != 0 {
					z = z + 1
				}
				for **(**Tu8)(__ccgo_up(z)) != 0 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(z))) != int32(']') {
					z = z + 1
				}
			} else {
				if libc.Int32FromUint8(c) != libc.Int32FromUint8(c1) && libc.Int32FromUint8(c) != libc.Int32FromUint8(c2) {
					sz = sz + 1
				}
			}
		}
		if sz > *(*int32)(unsafe.Pointer(pWalker + 24)) {
			*(*int32)(unsafe.Pointer(pWalker + 24)) = sz
		}
	}
	return WRC_Continue
}

// C documentation
//
//	/* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
//	**
//	** Set the 0x01 bit of pWalker->eCode if there is a reference to any
//	** of the tables shown in RefSrcList.pRef.
//	**
//	** Set the 0x02 bit of pWalker->eCode if there is a reference to a
//	** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
//	*/
func _exprRefToSrcList(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var i, nSrc, v1 int32
	var p, pSrc, v3 uintptr
	_, _, _, _, _, _ = i, nSrc, p, pSrc, v1, v3
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_COLUMN) {
		p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
		pSrc = (*TRefSrcList)(unsafe.Pointer(p)).FpRef
		if pSrc != 0 {
			v1 = (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc
		} else {
			v1 = 0
		}
		nSrc = v1
		i = 0
		for {
			if !(i < nSrc) {
				break
			}
			if (*TExpr)(unsafe.Pointer(pExpr)).FiTable == (*(*TSrcItem)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48))).FiCursor {
				v3 = pWalker + 20
				*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromInt32(1))
				return WRC_Continue
			}
			goto _2
		_2:
			;
			i = i + 1
		}
		i = 0
		for {
			if !(int64(i) < (*TRefSrcList)(unsafe.Pointer(p)).FnExclude && **(**int32)(__ccgo_up((*TRefSrcList)(unsafe.Pointer(p)).FaiExclude + uintptr(i)*4)) != (*TExpr)(unsafe.Pointer(pExpr)).FiTable) {
				break
			}
			goto _4
		_4:
			;
			i = i + 1
		}
		if int64(i) >= (*TRefSrcList)(unsafe.Pointer(p)).FnExclude {
			v3 = pWalker + 20
			*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromInt32(2))
		}
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Set the Expr.nHeight variable in the structure passed as an
//	** argument. An expression with no children, Expr.pList or
//	** Expr.pSelect member has a height of 1. Any other expression
//	** has a height equal to the maximum height of any other
//	** referenced Expr plus one.
//	**
//	** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
//	** if appropriate.
//	*/
func _exprSetHeight(tls *libc.TLS, p uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var v1 int32
	var _ /* nHeight at bp+0 */ int32
	_ = v1
	if (*TExpr)(unsafe.Pointer(p)).FpLeft != 0 {
		v1 = (*TExpr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).FpLeft)).FnHeight
	} else {
		v1 = 0
	}
	**(**int32)(__ccgo_up(bp)) = v1
	if (*TExpr)(unsafe.Pointer(p)).FpRight != 0 && (*TExpr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).FpRight)).FnHeight > **(**int32)(__ccgo_up(bp)) {
		**(**int32)(__ccgo_up(bp)) = (*TExpr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).FpRight)).FnHeight
	}
	if (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
		_heightOfSelect(tls, *(*uintptr)(unsafe.Pointer(p + 20)), bp)
	} else {
		if *(*uintptr)(unsafe.Pointer(p + 20)) != 0 {
			_heightOfExprList(tls, *(*uintptr)(unsafe.Pointer(p + 20)), bp)
			**(**Tu32)(__ccgo_up(p + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_Collate)|libc.Int32FromInt32(EP_Subquery)|libc.Int32FromInt32(EP_HasFunc)) & _sqlite3ExprListFlags(tls, *(*uintptr)(unsafe.Pointer(p + 20)))
		}
	}
	(*TExpr)(unsafe.Pointer(p)).FnHeight = **(**int32)(__ccgo_up(bp)) + int32(1)
}

// C documentation
//
//	/*
//	** Return the number of bytes allocated for the expression structure
//	** passed as the first argument. This is always one of EXPR_FULLSIZE,
//	** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
//	*/
func _exprStructSize(tls *libc.TLS, p uintptr) (r int32) {
	if (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)) != uint32(0) {
		return libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0) + 12))
	}
	if (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Reduced)) != uint32(0) {
		return libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0) + 28))
	}
	return int32(52)
}

// C documentation
//
//	/*
//	** Argument pVector points to a vector expression - either a TK_VECTOR
//	** or TK_SELECT that returns more than one column. This function returns
//	** the register number of a register that contains the value of
//	** element iField of the vector.
//	**
//	** If pVector is a TK_SELECT expression, then code for it must have
//	** already been generated using the exprCodeSubselect() routine. In this
//	** case parameter regSelect should be the first in an array of registers
//	** containing the results of the sub-select.
//	**
//	** If pVector is of type TK_VECTOR, then code for the requested field
//	** is generated. In this case (*pRegFree) may be set to the number of
//	** a temporary register to be freed by the caller before returning.
//	**
//	** Before returning, output parameter (*ppExpr) is set to point to the
//	** Expr object corresponding to element iElem of the vector.
//	*/
func _exprVectorRegister(tls *libc.TLS, pParse uintptr, pVector uintptr, iField int32, regSelect int32, ppExpr uintptr, pRegFree uintptr) (r int32) {
	var op Tu8
	_ = op
	op = (*TExpr)(unsafe.Pointer(pVector)).Fop
	if libc.Int32FromUint8(op) == int32(TK_REGISTER) {
		**(**uintptr)(__ccgo_up(ppExpr)) = _sqlite3VectorFieldSubexpr(tls, pVector, iField)
		return (*TExpr)(unsafe.Pointer(pVector)).FiTable + iField
	}
	if libc.Int32FromUint8(op) == int32(TK_SELECT) {
		**(**uintptr)(__ccgo_up(ppExpr)) = (*(*TExprList_item)(unsafe.Pointer((*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pVector + 20)))).FpEList + 8 + uintptr(iField)*20))).FpExpr
		return regSelect + iField
	}
	if libc.Int32FromUint8(op) == int32(TK_VECTOR) {
		**(**uintptr)(__ccgo_up(ppExpr)) = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pVector + 20)) + 8 + uintptr(iField)*20))).FpExpr
		return _sqlite3ExprCodeTemp(tls, pParse, **(**uintptr)(__ccgo_up(ppExpr)), pRegFree)
	}
	return 0
}

// C documentation
//
//	/*
//	** Create a new expression term for the column specified by pMatch and
//	** iColumn.  Append this new expression term to the FULL JOIN Match set
//	** in *ppList.  Create a new *ppList if this is the first term in the
//	** set.
//	*/
func _extendFJMatch(tls *libc.TLS, pParse uintptr, ppList uintptr, pMatch uintptr, iColumn Ti16) {
	var pNew uintptr
	_ = pNew
	pNew = _sqlite3ExprAlloc(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, int32(TK_COLUMN), uintptr(0), 0)
	if pNew != 0 {
		(*TExpr)(unsafe.Pointer(pNew)).FiTable = (*TSrcItem)(unsafe.Pointer(pMatch)).FiCursor
		(*TExpr)(unsafe.Pointer(pNew)).FiColumn = iColumn
		(*TExpr)(unsafe.Pointer(pNew)).Fy.FpTab = (*TSrcItem)(unsafe.Pointer(pMatch)).FpSTab
		**(**Tu32)(__ccgo_up(pNew + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_CanBeNull))
		**(**uintptr)(__ccgo_up(ppList)) = _sqlite3ExprListAppend(tls, pParse, **(**uintptr)(__ccgo_up(ppList)), pNew)
	}
}

// C documentation
//
//	/*
//	** Return a pointer to payload information from the entry that the
//	** pCur cursor is pointing to.  The pointer is to the beginning of
//	** the key if index btrees (pPage->intKey==0) and is the data for
//	** table btrees (pPage->intKey==1). The number of bytes of available
//	** key/data is written into *pAmt.  If *pAmt==0, then the value
//	** returned will not be a valid pointer.
//	**
//	** This routine is an optimization.  It is common for the entire key
//	** and data to fit on the local page and for there to be no overflow
//	** pages.  When that is so, this routine can be used to access the
//	** key and data without making a copy.  If the key and/or data spills
//	** onto overflow pages, then accessPayload() must be used to reassemble
//	** the key/data and copy it into a preallocated buffer.
//	**
//	** The pointer returned by this routine looks directly into the cached
//	** page of the database.  The data might change or move the next time
//	** any btree routine is called.
//	*/
func _fetchPayload(tls *libc.TLS, pCur uintptr, pAmt uintptr) (r uintptr) {
	var amt, v1 int32
	_, _ = amt, v1
	amt = libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnLocal)
	if amt > int32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FaDataEnd)-int32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload) {
		/* There is too little space on the page for the expected amount
		 ** of local content. Database must be corrupt. */
		if 0 > int32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FaDataEnd)-int32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload) {
			v1 = 0
		} else {
			v1 = int32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FaDataEnd) - int32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload)
		}
		amt = v1
	}
	**(**Tu32)(__ccgo_up(pAmt)) = libc.Uint32FromInt32(amt)
	return (*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload
}

// C documentation
//
//	/*
//	** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
//	** with pOp->p3.  Return the hash.
//	*/
func _filterHash(tls *libc.TLS, aMem uintptr, pOp uintptr) (r Tu64) {
	var h Tu64
	var i, mx int32
	var p uintptr
	_, _, _, _ = h, i, mx, p
	h = uint64(0)
	i = (*TOp)(unsafe.Pointer(pOp)).Fp3
	mx = i + *(*int32)(unsafe.Pointer(pOp + 16))
	for {
		if !(i < mx) {
			break
		}
		p = aMem + uintptr(i)*40
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_Int)|libc.Int32FromInt32(MEM_IntReal)) != 0 {
			h = h + libc.Uint64FromInt64(*(*Ti64)(unsafe.Pointer(p)))
		} else {
			if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&int32(MEM_Real) != 0 {
				h = h + libc.Uint64FromInt64(_sqlite3VdbeIntValue(tls, p))
			} else {
				if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_Str)|libc.Int32FromInt32(MEM_Blob)) != 0 {
					/* All strings have the same hash and all blobs have the same hash,
					 ** though, at least, those hashes are different from each other and
					 ** from NULL. */
					h = h + libc.Uint64FromInt32(int32(4093)+libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_Str)|libc.Int32FromInt32(MEM_Blob)))
				}
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return h
}

// C documentation
//
//	/*
//	** Invoke the OP_AggFinalize opcode for every aggregate function
//	** in the AggInfo structure.
//	*/
func _finalizeAggFunctions(tls *libc.TLS, pParse uintptr, pAggInfo uintptr) {
	var i, iBaseCol, iTop, j, nArg, nKey, regAgg, regSubtype, v4 int32
	var pF, pList, v uintptr
	_, _, _, _, _, _, _, _, _, _, _, _ = i, iBaseCol, iTop, j, nArg, nKey, pF, pList, regAgg, regSubtype, v, v4
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	i = 0
	pF = (*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc
	for {
		if !(i < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnFunc) {
			break
		}
		if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
			return
		}
		pList = *(*uintptr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr + 20))
		if (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab >= 0 { /* Loop counter */
			nArg = (*TExprList)(unsafe.Pointer(pList)).FnExpr
			regAgg = _sqlite3GetTempRange(tls, pParse, nArg)
			if libc.Int32FromUint8((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBPayload) == 0 {
				nKey = 0
			} else {
				nKey = (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer((*TExpr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr)).FpLeft + 20)))).FnExpr
				if !((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBUnique != 0) {
					nKey = nKey + 1
				}
			}
			iTop = _sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab)
			j = nArg - int32(1)
			for {
				if !(j >= 0) {
					break
				}
				_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab, nKey+j, regAgg+j)
				goto _2
			_2:
				;
				j = j - 1
			}
			if (*TAggInfo_func)(unsafe.Pointer(pF)).FbUseSubtype != 0 {
				regSubtype = _sqlite3GetTempReg(tls, pParse)
				iBaseCol = nKey + nArg + libc.BoolInt32(libc.Int32FromUint8((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBPayload) == 0 && libc.Int32FromUint8((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBUnique) == 0)
				j = nArg - int32(1)
				for {
					if !(j >= 0) {
						break
					}
					_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab, iBaseCol+j, regSubtype)
					_sqlite3VdbeAddOp2(tls, v, int32(OP_SetSubtype), regSubtype, regAgg+j)
					goto _3
				_3:
					;
					j = j - 1
				}
				_sqlite3ReleaseTempReg(tls, pParse, regSubtype)
			}
			_sqlite3VdbeAddOp3(tls, v, int32(OP_AggStep), 0, regAgg, (*TAggInfo)(unsafe.Pointer(pAggInfo)).FiFirstReg+(*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn+i)
			_sqlite3VdbeAppendP4(tls, v, (*TAggInfo_func)(unsafe.Pointer(pF)).FpFunc, -int32(8))
			_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(nArg))
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Next), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab, iTop+int32(1))
			_sqlite3VdbeJumpHere(tls, v, iTop)
			_sqlite3ReleaseTempRange(tls, pParse, regAgg, nArg)
		}
		if pList != 0 {
			v4 = (*TExprList)(unsafe.Pointer(pList)).FnExpr
		} else {
			v4 = 0
		}
		_sqlite3VdbeAddOp2(tls, v, int32(OP_AggFinal), (*TAggInfo)(unsafe.Pointer(pAggInfo)).FiFirstReg+(*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn+i, v4)
		_sqlite3VdbeAppendP4(tls, v, (*TAggInfo_func)(unsafe.Pointer(pF)).FpFunc, -int32(8))
		goto _1
	_1:
		;
		i = i + 1
		pF += 24
	}
}

// C documentation
//
//	/*
//	** Scan all previously generated bytecode looking for an OP_BeginSubrtn
//	** that is compatible with pExpr.  If found, add the y.sub values
//	** to pExpr and return true.  If not found, return false.
//	*/
func _findCompatibleInRhsSubrtn(tls *libc.TLS, pParse uintptr, pExpr uintptr, pNewSig uintptr) (r int32) {
	var pEnd, pOp, pSig, v uintptr
	_, _, _, _ = pEnd, pOp, pSig, v
	if pNewSig == uintptr(0) {
		return 0
	}
	if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FmSubrtnSig)&(int32(1)<<((*TSubrtnSig)(unsafe.Pointer(pNewSig)).FselId&int32(7))) == 0 {
		return 0
	}
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	pOp = _sqlite3VdbeGetOp(tls, v, int32(1))
	pEnd = _sqlite3VdbeGetLastOp(tls, v)
	for {
		if !(pOp < pEnd) {
			break
		}
		if int32((*TVdbeOp)(unsafe.Pointer(pOp)).Fp4type) != -int32(18) {
			goto _1
		}
		pSig = *(*uintptr)(unsafe.Pointer(pOp + 16))
		if !((*TSubrtnSig)(unsafe.Pointer(pSig)).FbComplete != 0) {
			goto _1
		}
		if (*TSubrtnSig)(unsafe.Pointer(pNewSig)).FselId != (*TSubrtnSig)(unsafe.Pointer(pSig)).FselId {
			goto _1
		}
		if libc.Xstrcmp(tls, (*TSubrtnSig)(unsafe.Pointer(pNewSig)).FzAff, (*TSubrtnSig)(unsafe.Pointer(pSig)).FzAff) != 0 {
			goto _1
		}
		(*(*struct {
			FiAddr     int32
			FregReturn int32
		})(unsafe.Pointer(pExpr + 44))).FiAddr = (*TSubrtnSig)(unsafe.Pointer(pSig)).FiAddr
		(*(*struct {
			FiAddr     int32
			FregReturn int32
		})(unsafe.Pointer(pExpr + 44))).FregReturn = (*TSubrtnSig)(unsafe.Pointer(pSig)).FregReturn
		(*TExpr)(unsafe.Pointer(pExpr)).FiTable = (*TSubrtnSig)(unsafe.Pointer(pSig)).FiTable
		**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_Subrtn))
		return int32(1)
		goto _1
	_1:
		;
		pOp += 20
	}
	return 0
}

// C documentation
//
//	/*
//	** This function searches pList for an entry that matches the iCol-th column
//	** of index pIdx.
//	**
//	** If such an expression is found, its index in pList->a[] is returned. If
//	** no expression is found, -1 is returned.
//	*/
func _findIndexCol(tls *libc.TLS, pParse uintptr, pList uintptr, iBase int32, pIdx uintptr, iCol int32) (r int32) {
	var i int32
	var p, pColl, zColl uintptr
	_, _, _, _ = i, p, pColl, zColl
	zColl = **(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FazColl + uintptr(iCol)*4))
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
			break
		}
		p = _sqlite3ExprSkipCollateAndLikely(tls, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FpExpr)
		if p != uintptr(0) && (libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_COLUMN) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_AGG_COLUMN)) && int32((*TExpr)(unsafe.Pointer(p)).FiColumn) == int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(iCol)*2))) && (*TExpr)(unsafe.Pointer(p)).FiTable == iBase {
			pColl = _sqlite3ExprNNCollSeq(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FpExpr)
			if 0 == _sqlite3StrICmp(tls, (*TCollSeq)(unsafe.Pointer(pColl)).FzName, zColl) {
				return i
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return -int32(1)
}

// C documentation
//
//	/*
//	** The second argument points to an FKey object representing a foreign key
//	** for which pTab is the parent table. An UPDATE statement against pTab
//	** is currently being processed. For each column of the table that is
//	** actually updated, the corresponding element in the aChange[] array
//	** is zero or greater (if a column is unmodified the corresponding element
//	** is set to -1). If the rowid column is modified by the UPDATE statement
//	** the bChngRowid argument is non-zero.
//	**
//	** This function returns true if any of the columns that are part of the
//	** parent key for FK constraint *p are modified.
//	*/
func _fkParentIsModified(tls *libc.TLS, pTab uintptr, p uintptr, aChange uintptr, bChngRowid int32) (r int32) {
	var i, iKey int32
	var pCol, zKey uintptr
	_, _, _, _ = i, iKey, pCol, zKey
	i = 0
	for {
		if !(i < (*TFKey)(unsafe.Pointer(p)).FnCol) {
			break
		}
		zKey = (*(*TsColMap)(unsafe.Pointer(p + 36 + uintptr(i)*8))).FzCol
		iKey = 0
		for {
			if !(iKey < int32((*TTable)(unsafe.Pointer(pTab)).FnCol)) {
				break
			}
			if **(**int32)(__ccgo_up(aChange + uintptr(iKey)*4)) >= 0 || iKey == int32((*TTable)(unsafe.Pointer(pTab)).FiPKey) && bChngRowid != 0 {
				pCol = (*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(iKey)*12
				if zKey != 0 {
					if 0 == _sqlite3StrICmp(tls, (*TColumn)(unsafe.Pointer(pCol)).FzCnName, zKey) {
						return int32(1)
					}
				} else {
					if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FcolFlags)&int32(COLFLAG_PRIMKEY) != 0 {
						return int32(1)
					}
				}
			}
			goto _2
		_2:
			;
			iKey = iKey + 1
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** This function is called to generate code executed when a row is deleted
//	** from the parent table of foreign key constraint pFKey and, if pFKey is
//	** deferred, when a row is inserted into the same table. When generating
//	** code for an SQL UPDATE operation, this function may be called twice -
//	** once to "delete" the old row and once to "insert" the new row.
//	**
//	** Parameter nIncr is passed -1 when inserting a row (as this may decrease
//	** the number of FK violations in the db) or +1 when deleting one (as this
//	** may increase the number of FK constraint problems).
//	**
//	** The code generated by this function scans through the rows in the child
//	** table that correspond to the parent table row being deleted or inserted.
//	** For each child row found, one of the following actions is taken:
//	**
//	**   Operation | FK type   | Action taken
//	**   --------------------------------------------------------------------------
//	**   DELETE      immediate   Increment the "immediate constraint counter".
//	**
//	**   INSERT      immediate   Decrement the "immediate constraint counter".
//	**
//	**   DELETE      deferred    Increment the "deferred constraint counter".
//	**
//	**   INSERT      deferred    Decrement the "deferred constraint counter".
//	**
//	** These operations are identified in the comment at the top of this file
//	** (fkey.c) as "I.2" and "D.2".
//	*/
func _fkScanChildren(tls *libc.TLS, pParse uintptr, pSrc uintptr, pTab uintptr, pIdx uintptr, pFKey uintptr, aiCol uintptr, regData int32, nIncr int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var db, pAll, pEq, pEq1, pLeft, pLeft1, pNe, pRight, pRight1, pWInfo, pWhere, v, zCol uintptr
	var i, iFkIfZero, v2 int32
	var iCol, iCol1 Ti16
	var _ /* sNameContext at bp+0 */ TNameContext
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = db, i, iCol, iCol1, iFkIfZero, pAll, pEq, pEq1, pLeft, pLeft1, pNe, pRight, pRight1, pWInfo, pWhere, v, zCol, v2
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb /* Iterator variable */
	pWhere = uintptr(0)                        /* Context used by sqlite3WhereXXX() */
	iFkIfZero = 0                              /* Address of OP_FkIfZero */
	v = _sqlite3GetVdbe(tls, pParse)
	if nIncr < 0 {
		iFkIfZero = _sqlite3VdbeAddOp2(tls, v, int32(OP_FkIfZero), libc.Int32FromUint8((*TFKey)(unsafe.Pointer(pFKey)).FisDeferred), 0)
	}
	/* Create an Expr object representing an SQL expression like:
	 **
	 **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
	 **
	 ** The collation sequence used for the comparison should be that of
	 ** the parent key columns. The affinity of the parent key column should
	 ** be applied to each child key value before the comparison takes place.
	 */
	i = 0
	for {
		if !(i < (*TFKey)(unsafe.Pointer(pFKey)).FnCol) {
			break
		} /* Name of column in child table */
		if pIdx != 0 {
			v2 = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2)))
		} else {
			v2 = -int32(1)
		}
		iCol = int16(v2)
		pLeft = _exprTableRegister(tls, pParse, pTab, regData, iCol)
		if aiCol != 0 {
			v2 = **(**int32)(__ccgo_up(aiCol + uintptr(i)*4))
		} else {
			v2 = (*(*TsColMap)(unsafe.Pointer(pFKey + 36))).FiFrom
		}
		iCol = int16(v2)
		zCol = (**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer((*TFKey)(unsafe.Pointer(pFKey)).FpFrom)).FaCol + uintptr(iCol)*12))).FzCnName
		pRight = _sqlite3Expr(tls, db, int32(TK_ID), zCol)
		pEq = _sqlite3PExpr(tls, pParse, int32(TK_EQ), pLeft, pRight)
		pWhere = _sqlite3ExprAnd(tls, pParse, pWhere, pEq)
		goto _1
	_1:
		;
		i = i + 1
	}
	/* If the child table is the same as the parent table, then add terms
	 ** to the WHERE clause that prevent this entry from being scanned.
	 ** The added WHERE clause terms are like this:
	 **
	 **     $current_rowid!=rowid
	 **     NOT( $current_a==a AND $current_b==b AND ... )
	 **
	 ** The first form is used for rowid tables.  The second form is used
	 ** for WITHOUT ROWID tables. In the second form, the *parent* key is
	 ** (a,b,...). Either the parent or primary key could be used to
	 ** uniquely identify the current row, but the parent key is more convenient
	 ** as the required values have already been loaded into registers
	 ** by the caller.
	 */
	if pTab == (*TFKey)(unsafe.Pointer(pFKey)).FpFrom && nIncr > 0 { /* Column ref to child table */
		if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_WithoutRowid) == uint32(0) {
			pLeft1 = _exprTableRegister(tls, pParse, pTab, regData, int16(-int32(1)))
			pRight1 = _exprTableColumn(tls, db, pTab, (*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FiCursor, int16(-int32(1)))
			pNe = _sqlite3PExpr(tls, pParse, int32(TK_NE), pLeft1, pRight1)
		} else {
			pAll = uintptr(0)
			i = 0
			for {
				if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)) {
					break
				}
				iCol1 = **(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2))
				pLeft1 = _exprTableRegister(tls, pParse, pTab, regData, iCol1)
				pRight1 = _sqlite3Expr(tls, db, int32(TK_ID), (**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(iCol1)*12))).FzCnName)
				pEq1 = _sqlite3PExpr(tls, pParse, int32(TK_IS), pLeft1, pRight1)
				pAll = _sqlite3ExprAnd(tls, pParse, pAll, pEq1)
				goto _4
			_4:
				;
				i = i + 1
			}
			pNe = _sqlite3PExpr(tls, pParse, int32(TK_NOT), pAll, uintptr(0))
		}
		pWhere = _sqlite3ExprAnd(tls, pParse, pWhere, pNe)
	}
	/* Resolve the references in the WHERE clause. */
	libc.Xmemset(tls, bp, 0, uint32(36))
	(**(**TNameContext)(__ccgo_up(bp))).FpSrcList = pSrc
	(**(**TNameContext)(__ccgo_up(bp))).FpParse = pParse
	_sqlite3ResolveExprNames(tls, bp, pWhere)
	/* Create VDBE to loop through the entries in pSrc that match the WHERE
	 ** clause. For each row found, increment either the deferred or immediate
	 ** foreign key constraint counter. */
	if (*TParse)(unsafe.Pointer(pParse)).FnErr == 0 {
		pWInfo = _sqlite3WhereBegin(tls, pParse, pSrc, pWhere, uintptr(0), uintptr(0), uintptr(0), uint16(0), 0)
		_sqlite3VdbeAddOp2(tls, v, int32(OP_FkCounter), libc.Int32FromUint8((*TFKey)(unsafe.Pointer(pFKey)).FisDeferred), nIncr)
		if pWInfo != 0 {
			_sqlite3WhereEnd(tls, pWInfo)
		}
	}
	/* Clean up the WHERE clause constructed above. */
	_sqlite3ExprDelete(tls, db, pWhere)
	if iFkIfZero != 0 {
		_sqlite3VdbeJumpHereOrPopInst(tls, v, iFkIfZero)
	}
}

// C documentation
//
//	/*
//	** This routine attempts to flatten subqueries as a performance optimization.
//	** This routine returns 1 if it makes changes and 0 if no flattening occurs.
//	**
//	** To understand the concept of flattening, consider the following
//	** query:
//	**
//	**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
//	**
//	** The default way of implementing this query is to execute the
//	** subquery first and store the results in a temporary table, then
//	** run the outer query on that temporary table.  This requires two
//	** passes over the data.  Furthermore, because the temporary table
//	** has no indices, the WHERE clause on the outer query cannot be
//	** optimized.
//	**
//	** This routine attempts to rewrite queries such as the above into
//	** a single flat select, like this:
//	**
//	**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
//	**
//	** The code generated for this simplification gives the same result
//	** but only has to scan the data once.  And because indices might
//	** exist on the table t1, a complete scan of the data might be
//	** avoided.
//	**
//	** Flattening is subject to the following constraints:
//	**
//	**  (**)  We no longer attempt to flatten aggregate subqueries. Was:
//	**        The subquery and the outer query cannot both be aggregates.
//	**
//	**  (**)  We no longer attempt to flatten aggregate subqueries. Was:
//	**        (2) If the subquery is an aggregate then
//	**        (2a) the outer query must not be a join and
//	**        (2b) the outer query must not use subqueries
//	**             other than the one FROM-clause subquery that is a candidate
//	**             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
//	**             from 2015-02-09.)
//	**
//	**   (3)  If the subquery is the right operand of a LEFT JOIN then
//	**        (3a) the subquery may not be a join
//	**        (**) Was (3b): "the FROM clause of the subquery may not contain
//	**             a virtual table"
//	**        (**) Was: "The outer query may not have a GROUP BY." This case
//	**             is now managed correctly
//	**        (3d) the outer query may not be DISTINCT.
//	**        See also (26) for restrictions on RIGHT JOIN.
//	**
//	**   (4)  The subquery can not be DISTINCT.
//	**
//	**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
//	**        sub-queries that were excluded from this optimization. Restriction
//	**        (4) has since been expanded to exclude all DISTINCT subqueries.
//	**
//	**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
//	**        If the subquery is aggregate, the outer query may not be DISTINCT.
//	**
//	**   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
//	**        A FROM clause, consider adding a FROM clause with the special
//	**        table sqlite_once that consists of a single row containing a
//	**        single NULL.
//	**
//	**   (8)  If the subquery uses LIMIT then the outer query may not be a join.
//	**
//	**   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
//	**
//	**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
//	**        accidentally carried the comment forward until 2014-09-15.  Original
//	**        constraint: "If the subquery is aggregate then the outer query
//	**        may not use LIMIT."
//	**
//	**  (11)  The subquery and the outer query may not both have ORDER BY clauses.
//	**
//	**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
//	**        a separate restriction deriving from ticket #350.
//	**
//	**  (13)  The subquery and outer query may not both use LIMIT.
//	**
//	**  (14)  The subquery may not use OFFSET.
//	**
//	**  (15)  If the outer query is part of a compound select, then the
//	**        subquery may not use LIMIT.
//	**        (See ticket #2339 and ticket [02a8e81d44]).
//	**
//	**  (16)  If the outer query is aggregate, then the subquery may not
//	**        use ORDER BY.  (Ticket #2942)  This used to not matter
//	**        until we introduced the group_concat() function.
//	**
//	**  (17)  If the subquery is a compound select, then
//	**        (17a) all compound operators must be a UNION ALL, and
//	**        (17b) no terms within the subquery compound may be aggregate
//	**              or DISTINCT, and
//	**        (17c) every term within the subquery compound must have a FROM clause
//	**        (17d) the outer query may not be
//	**              (17d1) aggregate, or
//	**              (17d2) DISTINCT
//	**        (17e) the subquery may not contain window functions, and
//	**        (17f) the subquery must not be the RHS of a LEFT JOIN.
//	**        (17g) either the subquery is the first element of the outer
//	**              query or there are no RIGHT or FULL JOINs in any arm
//	**              of the subquery.  (This is a duplicate of condition (27b).)
//	**        (17h) The corresponding result set expressions in all arms of the
//	**              compound must have the same affinity.
//	**
//	**        The parent and sub-query may contain WHERE clauses. Subject to
//	**        rules (11), (13) and (14), they may also contain ORDER BY,
//	**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
//	**        operator other than UNION ALL because all the other compound
//	**        operators have an implied DISTINCT which is disallowed by
//	**        restriction (4).
//	**
//	**        Also, each component of the sub-query must return the same number
//	**        of result columns. This is actually a requirement for any compound
//	**        SELECT statement, but all the code here does is make sure that no
//	**        such (illegal) sub-query is flattened. The caller will detect the
//	**        syntax error and return a detailed message.
//	**
//	**  (18)  If the sub-query is a compound select, then all terms of the
//	**        ORDER BY clause of the parent must be copies of a term returned
//	**        by the parent query.
//	**
//	**  (19)  If the subquery uses LIMIT then the outer query may not
//	**        have a WHERE clause.
//	**
//	**  (20)  If the sub-query is a compound select, then it must not use
//	**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
//	**        somewhat by saying that the terms of the ORDER BY clause must
//	**        appear as unmodified result columns in the outer query.  But we
//	**        have other optimizations in mind to deal with that case.
//	**
//	**  (21)  If the subquery uses LIMIT then the outer query may not be
//	**        DISTINCT.  (See ticket [752e1646fc]).
//	**
//	**  (22)  The subquery may not be a recursive CTE.
//	**
//	**  (23)  If the outer query is a recursive CTE, then the sub-query may not be
//	**        a compound query.  This restriction is because transforming the
//	**        parent to a compound query confuses the code that handles
//	**        recursive queries in multiSelect().
//	**
//	**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
//	**        The subquery may not be an aggregate that uses the built-in min() or
//	**        or max() functions.  (Without this restriction, a query like:
//	**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
//	**        return the value X for which Y was maximal.)
//	**
//	**  (25)  If either the subquery or the parent query contains a window
//	**        function in the select list or ORDER BY clause, flattening
//	**        is not attempted.
//	**
//	**  (26)  The subquery may not be the right operand of a RIGHT JOIN.
//	**        See also (3) for restrictions on LEFT JOIN.
//	**
//	**  (27)  The subquery may not contain a FULL or RIGHT JOIN unless it
//	**        is the first element of the parent query.  Two subcases:
//	**        (27a) the subquery is not a compound query.
//	**        (27b) the subquery is a compound query and the RIGHT JOIN occurs
//	**              in any arm of the compound query.  (See also (17g).)
//	**
//	**  (28)  The subquery is not a MATERIALIZED CTE.  (This is handled
//	**        in the caller before ever reaching this routine.)
//	**
//	**
//	** In this routine, the "p" parameter is a pointer to the outer query.
//	** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
//	** uses aggregates.
//	**
//	** If flattening is not attempted, this routine is a no-op and returns 0.
//	** If flattening is attempted this routine returns 1.
//	**
//	** All of the expression analysis must occur on both the outer query and
//	** the subquery before this routine runs.
//	*/
func _flattenSubquery(tls *libc.TLS, pParse uintptr, p uintptr, iFrom int32, isAgg int32) (r int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var aCsrMap, db, pItem, pItemTab, pLimit, pNew, pOrderBy, pOrderBy1, pParent, pPrior, pSrc, pSub, pSub1, pSubSrc, pSubitem, pTabToDel, pToplevel, pWhere, zSavedAuthContext, v5 uintptr
	var i, iNewParent, iParent, ii, isOuterJoin, nSubSrc, v4 int32
	var jointype Tu8
	var _ /* w at bp+0 */ TWalker
	var _ /* x at bp+28 */ TSubstContext
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aCsrMap, db, i, iNewParent, iParent, ii, isOuterJoin, jointype, nSubSrc, pItem, pItemTab, pLimit, pNew, pOrderBy, pOrderBy1, pParent, pPrior, pSrc, pSub, pSub1, pSubSrc, pSubitem, pTabToDel, pToplevel, pWhere, zSavedAuthContext, v4, v5
	zSavedAuthContext = (*TParse)(unsafe.Pointer(pParse)).FzAuthContext /* VDBE cursor number of the pSub result set temp table */
	iNewParent = -int32(1)                                              /* Replacement table for iParent */
	isOuterJoin = 0                                                     /* The subquery */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb                          /* Walker to persist agginfo data */
	aCsrMap = uintptr(0)
	/* Check to see if flattening is permitted.  Return 0 if not.
	 */
	if (*Tsqlite3)(unsafe.Pointer(db)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_QueryFlattener)) != uint32(0) {
		return 0
	}
	pSrc = (*TSelect)(unsafe.Pointer(p)).FpSrc
	pSubitem = pSrc + 8 + uintptr(iFrom)*48
	iParent = (*TSrcItem)(unsafe.Pointer(pSubitem)).FiCursor
	pSub = (*TSubquery)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pSubitem + 44)))).FpSelect
	if (*TSelect)(unsafe.Pointer(p)).FpWin != 0 || (*TSelect)(unsafe.Pointer(pSub)).FpWin != 0 {
		return 0
	} /* Restriction (25) */
	pSubSrc = (*TSelect)(unsafe.Pointer(pSub)).FpSrc
	/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
	 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
	 ** because they could be computed at compile-time.  But when LIMIT and OFFSET
	 ** became arbitrary expressions, we were forced to add restrictions (13)
	 ** and (14). */
	if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 && (*TSelect)(unsafe.Pointer(p)).FpLimit != 0 {
		return 0
	} /* Restriction (13) */
	if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 && (*TExpr)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSub)).FpLimit)).FpRight != 0 {
		return 0
	} /* Restriction (14) */
	if (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Compound) != uint32(0) && (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 {
		return 0 /* Restriction (15) */
	}
	if (*TSrcList)(unsafe.Pointer(pSubSrc)).FnSrc == 0 {
		return 0
	} /* Restriction (7)  */
	if (*TSelect)(unsafe.Pointer(pSub)).FselFlags&uint32(SF_Distinct) != 0 {
		return 0
	} /* Restriction (4)  */
	if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 && ((*TSrcList)(unsafe.Pointer(pSrc)).FnSrc > int32(1) || isAgg != 0) {
		return 0 /* Restrictions (8)(9) */
	}
	if (*TSelect)(unsafe.Pointer(p)).FpOrderBy != 0 && (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy != 0 {
		return 0 /* Restriction (11) */
	}
	if isAgg != 0 && (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy != 0 {
		return 0
	} /* Restriction (16) */
	if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 && (*TSelect)(unsafe.Pointer(p)).FpWhere != 0 {
		return 0
	} /* Restriction (19) */
	if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 && (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Distinct) != uint32(0) {
		return 0 /* Restriction (21) */
	}
	if (*TSelect)(unsafe.Pointer(pSub)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Recursive)) != 0 {
		return 0 /* Restrictions (22) */
	}
	/*
	 ** If the subquery is the right operand of a LEFT JOIN, then the
	 ** subquery may not be a join itself (3a). Example of why this is not
	 ** allowed:
	 **
	 **         t1 LEFT OUTER JOIN (t2 JOIN t3)
	 **
	 ** If we flatten the above, we would get
	 **
	 **         (t1 LEFT OUTER JOIN t2) JOIN t3
	 **
	 ** which is not at all the same thing.
	 **
	 ** See also tickets #306, #350, and #3300.
	 */
	if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSubitem)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_OUTER)|libc.Int32FromInt32(JT_LTORJ)) != 0 {
		if (*TSrcList)(unsafe.Pointer(pSubSrc)).FnSrc > int32(1) || (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Distinct) != uint32(0) || libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSubitem)).Ffg.Fjointype)&int32(JT_RIGHT) != 0 {
			return 0
		}
		isOuterJoin = int32(1)
	}
	/* True by restriction (7) */
	if iFrom > 0 && libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(pSubSrc + 8))).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
		return 0 /* Restriction (27a) */
	}
	/* Condition (28) is blocked by the caller */
	/* Restriction (17): If the sub-query is a compound SELECT, then it must
	 ** use only the UNION ALL operator. And none of the simple select queries
	 ** that make up the compound SELECT are allowed to be aggregate or distinct
	 ** queries.
	 */
	if (*TSelect)(unsafe.Pointer(pSub)).FpPrior != 0 {
		if (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy != 0 {
			return 0 /* Restriction (20) */
		}
		if isAgg != 0 || (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Distinct) != uint32(0) || isOuterJoin > 0 {
			return 0 /* (17d1), (17d2), or (17f) */
		}
		pSub1 = pSub
		for {
			if !(pSub1 != 0) {
				break
			}
			if (*TSelect)(unsafe.Pointer(pSub1)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Distinct)|libc.Int32FromInt32(SF_Aggregate)) != uint32(0) || (*TSelect)(unsafe.Pointer(pSub1)).FpPrior != 0 && libc.Int32FromUint8((*TSelect)(unsafe.Pointer(pSub1)).Fop) != int32(TK_ALL) || (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSub1)).FpSrc)).FnSrc < int32(1) || (*TSelect)(unsafe.Pointer(pSub1)).FpWin != 0 {
				return 0
			}
			if iFrom > 0 && libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSub1)).FpSrc + 8))).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
				/* Without this restriction, the JT_LTORJ flag would end up being
				 ** omitted on left-hand tables of the right join that is being
				 ** flattened. */
				return 0 /* Restrictions (17g), (27b) */
			}
			goto _1
		_1:
			;
			pSub1 = (*TSelect)(unsafe.Pointer(pSub1)).FpPrior
		}
		/* Restriction (18). */
		if (*TSelect)(unsafe.Pointer(p)).FpOrderBy != 0 {
			ii = 0
			for {
				if !(ii < (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpOrderBy)).FnExpr) {
					break
				}
				if libc.Int32FromUint16(*(*Tu16)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpOrderBy + 8 + uintptr(ii)*20 + 16))) == 0 {
					return 0
				}
				goto _2
			_2:
				;
				ii = ii + 1
			}
		}
		/* Restriction (23) */
		if (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Recursive) != 0 {
			return 0
		}
		/* Restriction (17h) */
		if _compoundHasDifferentAffinities(tls, pSub) != 0 {
			return 0
		}
		if (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc > int32(1) {
			if (*TParse)(unsafe.Pointer(pParse)).FnSelect > int32(500) {
				return 0
			}
			if (*Tsqlite3)(unsafe.Pointer(db)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_FlttnUnionAll)) != uint32(0) {
				return 0
			}
			aCsrMap = _sqlite3DbMallocZero(tls, db, libc.Uint64FromInt64((int64((*TParse)(unsafe.Pointer(pParse)).FnTab)+int64(1))*int64(4)))
			if aCsrMap != 0 {
				**(**int32)(__ccgo_up(aCsrMap)) = (*TParse)(unsafe.Pointer(pParse)).FnTab
			}
		}
	}
	/***** If we reach this point, flattening is permitted. *****/
	/* Authorize the subquery */
	(*TParse)(unsafe.Pointer(pParse)).FzAuthContext = (*TSrcItem)(unsafe.Pointer(pSubitem)).FzName
	_sqlite3AuthCheck(tls, pParse, int32(SQLITE_SELECT), uintptr(0), uintptr(0), uintptr(0))
	(*TParse)(unsafe.Pointer(pParse)).FzAuthContext = zSavedAuthContext
	/* Delete the transient structures associated with the subquery */
	if int32(*(*uint32)(unsafe.Pointer(pSubitem + 12 + 4))&0x4>>2) != 0 {
		pSub1 = _sqlite3SubqueryDetach(tls, db, pSubitem)
	} else {
		pSub1 = uintptr(0)
	}
	_sqlite3DbFree(tls, db, (*TSrcItem)(unsafe.Pointer(pSubitem)).FzName)
	_sqlite3DbFree(tls, db, (*TSrcItem)(unsafe.Pointer(pSubitem)).FzAlias)
	(*TSrcItem)(unsafe.Pointer(pSubitem)).FzName = uintptr(0)
	(*TSrcItem)(unsafe.Pointer(pSubitem)).FzAlias = uintptr(0)
	/* If the sub-query is a compound SELECT statement, then (by restrictions
	 ** 17 and 18 above) it must be a UNION ALL and the parent query must
	 ** be of the form:
	 **
	 **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
	 **
	 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
	 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
	 ** OFFSET clauses and joins them to the left-hand-side of the original
	 ** using UNION ALL operators. In this case N is the number of simple
	 ** select statements in the compound sub-query.
	 **
	 ** Example:
	 **
	 **     SELECT a+1 FROM (
	 **        SELECT x FROM tab
	 **        UNION ALL
	 **        SELECT y FROM tab
	 **        UNION ALL
	 **        SELECT abs(z*2) FROM tab2
	 **     ) WHERE a!=5 ORDER BY 1
	 **
	 ** Transformed into:
	 **
	 **     SELECT x+1 FROM tab WHERE x+1!=5
	 **     UNION ALL
	 **     SELECT y+1 FROM tab WHERE y+1!=5
	 **     UNION ALL
	 **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
	 **     ORDER BY 1
	 **
	 ** We call this the "compound-subquery flattening".
	 */
	pSub = (*TSelect)(unsafe.Pointer(pSub)).FpPrior
	for {
		if !(pSub != 0) {
			break
		}
		pOrderBy = (*TSelect)(unsafe.Pointer(p)).FpOrderBy
		pLimit = (*TSelect)(unsafe.Pointer(p)).FpLimit
		pPrior = (*TSelect)(unsafe.Pointer(p)).FpPrior
		pItemTab = (*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab
		(*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab = uintptr(0)
		(*TSelect)(unsafe.Pointer(p)).FpOrderBy = uintptr(0)
		(*TSelect)(unsafe.Pointer(p)).FpPrior = uintptr(0)
		(*TSelect)(unsafe.Pointer(p)).FpLimit = uintptr(0)
		pNew = _sqlite3SelectDup(tls, db, p, 0)
		(*TSelect)(unsafe.Pointer(p)).FpLimit = pLimit
		(*TSelect)(unsafe.Pointer(p)).FpOrderBy = pOrderBy
		(*TSelect)(unsafe.Pointer(p)).Fop = uint8(TK_ALL)
		(*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab = pItemTab
		if pNew == uintptr(0) {
			(*TSelect)(unsafe.Pointer(p)).FpPrior = pPrior
		} else {
			v5 = pParse + 100
			*(*int32)(unsafe.Pointer(v5)) = *(*int32)(unsafe.Pointer(v5)) + 1
			v4 = *(*int32)(unsafe.Pointer(v5))
			(*TSelect)(unsafe.Pointer(pNew)).FselId = libc.Uint32FromInt32(v4)
			if aCsrMap != 0 && libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
				_renumberCursors(tls, pParse, pNew, iFrom, aCsrMap)
			}
			(*TSelect)(unsafe.Pointer(pNew)).FpPrior = pPrior
			if pPrior != 0 {
				(*TSelect)(unsafe.Pointer(pPrior)).FpNext = pNew
			}
			(*TSelect)(unsafe.Pointer(pNew)).FpNext = p
			(*TSelect)(unsafe.Pointer(p)).FpPrior = pNew
		}
		goto _3
	_3:
		;
		pSub = (*TSelect)(unsafe.Pointer(pSub)).FpPrior
	}
	_sqlite3DbFree(tls, db, aCsrMap)
	if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
		_sqlite3SrcItemAttachSubquery(tls, pParse, pSubitem, pSub1, 0)
		return int32(1)
	}
	/* Defer deleting the Table object associated with the
	 ** subquery until code generation is
	 ** complete, since there may still exist Expr.pTab entries that
	 ** refer to the subquery even after flattening.  Ticket #3346.
	 **
	 ** pSubitem->pSTab is always non-NULL by test restrictions and tests above.
	 */
	if (*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab != uintptr(0) {
		pTabToDel = (*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab
		if (*TTable)(unsafe.Pointer(pTabToDel)).FnTabRef == uint32(1) {
			if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
				v5 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
			} else {
				v5 = pParse
			}
			pToplevel = v5
			_sqlite3ParserAddCleanup(tls, pToplevel, __ccgo_fp(_sqlite3DeleteTableGeneric), pTabToDel)
		} else {
			(*TTable)(unsafe.Pointer(pTabToDel)).FnTabRef = (*TTable)(unsafe.Pointer(pTabToDel)).FnTabRef - 1
		}
		(*TSrcItem)(unsafe.Pointer(pSubitem)).FpSTab = uintptr(0)
	}
	/* The following loop runs once for each term in a compound-subquery
	 ** flattening (as described above).  If we are doing a different kind
	 ** of flattening - a flattening other than a compound-subquery flattening -
	 ** then this loop only runs once.
	 **
	 ** This loop moves all of the FROM elements of the subquery into the
	 ** the FROM clause of the outer query.  Before doing this, remember
	 ** the cursor number for the original outer query FROM element in
	 ** iParent.  The iParent cursor will never be used.  Subsequent code
	 ** will scan expressions looking for iParent references and replace
	 ** those references with expressions that resolve to the subquery FROM
	 ** elements we are now copying in.
	 */
	pSub = pSub1
	pParent = p
	for {
		if !(pParent != 0) {
			break
		}
		jointype = (*TSrcItem)(unsafe.Pointer(pSubitem)).Ffg.Fjointype
		pSubSrc = (*TSelect)(unsafe.Pointer(pSub)).FpSrc     /* FROM clause of subquery */
		nSubSrc = (*TSrcList)(unsafe.Pointer(pSubSrc)).FnSrc /* Number of terms in subquery FROM clause */
		pSrc = (*TSelect)(unsafe.Pointer(pParent)).FpSrc     /* FROM clause of the outer query */
		/* The subquery uses a single slot of the FROM clause of the outer
		 ** query.  If the subquery has more than one element in its FROM clause,
		 ** then expand the outer query to make space for it to hold all elements
		 ** of the subquery.
		 **
		 ** Example:
		 **
		 **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
		 **
		 ** The outer query has 3 slots in its FROM clause.  One slot of the
		 ** outer query (the middle slot) is used by the subquery.  The next
		 ** block of code will expand the outer query FROM clause to 4 slots.
		 ** The middle slot is expanded to two slots in order to make space
		 ** for the two elements in the FROM clause of the subquery.
		 */
		if nSubSrc > int32(1) {
			pSrc = _sqlite3SrcListEnlarge(tls, pParse, pSrc, nSubSrc-int32(1), iFrom+int32(1))
			if pSrc == uintptr(0) {
				break
			}
			(*TSelect)(unsafe.Pointer(pParent)).FpSrc = pSrc
			pSubitem = pSrc + 8 + uintptr(iFrom)*48
		}
		/* Transfer the FROM clause terms from the subquery into the
		 ** outer query.
		 */
		iNewParent = (*(*TSrcItem)(unsafe.Pointer(pSubSrc + 8))).FiCursor
		i = 0
		for {
			if !(i < nSubSrc) {
				break
			}
			pItem = pSrc + 8 + uintptr(i+iFrom)*48
			if int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x800>>11) != 0 {
				_sqlite3IdListDelete(tls, db, *(*uintptr)(unsafe.Pointer(pItem + 40)))
			}
			**(**TSrcItem)(__ccgo_up(pItem)) = *(*TSrcItem)(unsafe.Pointer(pSubSrc + 8 + uintptr(i)*48))
			v5 = pItem + 12
			*(*Tu8)(unsafe.Pointer(v5)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v5))) | libc.Int32FromUint8(jointype)&libc.Int32FromInt32(JT_LTORJ))
			libc.Xmemset(tls, pSubSrc+8+uintptr(i)*48, 0, uint32(48))
			goto _8
		_8:
			;
			i = i + 1
		}
		v5 = pSubitem + 12
		*(*Tu8)(unsafe.Pointer(v5)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v5))) | libc.Int32FromUint8(jointype))
		/* Begin substituting subquery result set expressions for
		 ** references to the iParent in the outer query.
		 **
		 ** Example:
		 **
		 **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
		 **   \                     \_____________ subquery __________/          /
		 **    \_____________________ outer query ______________________________/
		 **
		 ** We look at every expression in the outer query and every place we see
		 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
		 */
		if (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy != 0 {
			/* At this point, any non-zero iOrderByCol values indicate that the
			 ** ORDER BY column expression is identical to the iOrderByCol'th
			 ** expression returned by SELECT statement pSub. Since these values
			 ** do not necessarily correspond to columns in SELECT statement pParent,
			 ** zero them before transferring the ORDER BY clause.
			 **
			 ** Not doing this may cause an error if a subsequent call to this
			 ** function attempts to flatten a compound sub-query into pParent.
			 ** See ticket [d11a6e908f].
			 */
			pOrderBy1 = (*TSelect)(unsafe.Pointer(pSub)).FpOrderBy
			i = 0
			for {
				if !(i < (*TExprList)(unsafe.Pointer(pOrderBy1)).FnExpr) {
					break
				}
				*(*Tu16)(unsafe.Pointer(pOrderBy1 + 8 + uintptr(i)*20 + 16)) = uint16(0)
				goto _11
			_11:
				;
				i = i + 1
			}
			(*TSelect)(unsafe.Pointer(pParent)).FpOrderBy = pOrderBy1
			(*TSelect)(unsafe.Pointer(pSub)).FpOrderBy = uintptr(0)
		}
		pWhere = (*TSelect)(unsafe.Pointer(pSub)).FpWhere
		(*TSelect)(unsafe.Pointer(pSub)).FpWhere = uintptr(0)
		if isOuterJoin > 0 {
			_sqlite3SetJoinExpr(tls, pWhere, iNewParent, uint32(EP_OuterON))
		}
		if pWhere != 0 {
			if (*TSelect)(unsafe.Pointer(pParent)).FpWhere != 0 {
				(*TSelect)(unsafe.Pointer(pParent)).FpWhere = _sqlite3PExpr(tls, pParse, int32(TK_AND), pWhere, (*TSelect)(unsafe.Pointer(pParent)).FpWhere)
			} else {
				(*TSelect)(unsafe.Pointer(pParent)).FpWhere = pWhere
			}
		}
		if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FpParse = pParse
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FiTable = iParent
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FiNewTable = iNewParent
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FisOuterJoin = isOuterJoin
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FnSelDepth = 0
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FpEList = (*TSelect)(unsafe.Pointer(pSub)).FpEList
			(**(**TSubstContext)(__ccgo_up(bp + 28))).FpCList = _findLeftmostExprlist(tls, pSub)
			_substSelect(tls, bp+28, pParent, 0)
		}
		/* The flattened query is a compound if either the inner or the
		 ** outer query is a compound. */
		**(**Tu32)(__ccgo_up(pParent + 4)) |= (*TSelect)(unsafe.Pointer(pSub)).FselFlags & uint32(SF_Compound)
		/* restriction (17b) */
		/*
		 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
		 **
		 ** One is tempted to try to add a and b to combine the limits.  But this
		 ** does not work if either limit is negative.
		 */
		if (*TSelect)(unsafe.Pointer(pSub)).FpLimit != 0 {
			(*TSelect)(unsafe.Pointer(pParent)).FpLimit = (*TSelect)(unsafe.Pointer(pSub)).FpLimit
			(*TSelect)(unsafe.Pointer(pSub)).FpLimit = uintptr(0)
		}
		/* Recompute the SrcItem.colUsed masks for the flattened
		 ** tables. */
		i = 0
		for {
			if !(i < nSubSrc) {
				break
			}
			_recomputeColumnsUsed(tls, pParent, pSrc+8+uintptr(i+iFrom)*48)
			goto _12
		_12:
			;
			i = i + 1
		}
		goto _7
	_7:
		;
		pParent = (*TSelect)(unsafe.Pointer(pParent)).FpPrior
		pSub = (*TSelect)(unsafe.Pointer(pSub)).FpPrior
	}
	/* Finally, delete what is left of the subquery and return success.
	 */
	_sqlite3AggInfoPersistWalkerInit(tls, bp, pParse)
	_sqlite3WalkSelect(tls, bp, pSub1)
	_sqlite3SelectDelete(tls, db, pSub1)
	return int32(1)
}

// C documentation
//
//	/*
//	** This function is used to add page iPage to the database file free-list.
//	** It is assumed that the page is not already a part of the free-list.
//	**
//	** The value passed as the second argument to this function is optional.
//	** If the caller happens to have a pointer to the MemPage object
//	** corresponding to page iPage handy, it may pass it as the second value.
//	** Otherwise, it may pass NULL.
//	**
//	** If a pointer to a MemPage object is passed as the second argument,
//	** its reference count is not altered by this function.
//	*/
func _freePage2(tls *libc.TLS, pBt uintptr, pMemPage uintptr, iPage TPgno) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iTrunk TPgno
	var nFree, nLeaf Tu32
	var pPage1 uintptr
	var v1, v3 int32
	var v2, v4 bool
	var _ /* pPage at bp+4 */ uintptr
	var _ /* pTrunk at bp+0 */ uintptr
	var _ /* rc at bp+8 */ int32
	_, _, _, _, _, _, _, _ = iTrunk, nFree, nLeaf, pPage1, v1, v2, v3, v4
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)          /* Free-list trunk page */
	iTrunk = uint32(0)                                 /* Page number of free-list trunk page */
	pPage1 = (*TBtShared)(unsafe.Pointer(pBt)).FpPage1 /* Initial number of pages on free-list */
	if iPage < uint32(2) || iPage > (*TBtShared)(unsafe.Pointer(pBt)).FnPage {
		return _sqlite3CorruptError(tls, int32(80075))
	}
	if pMemPage != 0 {
		**(**uintptr)(__ccgo_up(bp + 4)) = pMemPage
		_sqlite3PagerRef(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage)
	} else {
		**(**uintptr)(__ccgo_up(bp + 4)) = _btreePageLookup(tls, pBt, iPage)
	}
	/* Increment the free page count on pPage1 */
	**(**int32)(__ccgo_up(bp + 8)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FpDbPage)
	if **(**int32)(__ccgo_up(bp + 8)) != 0 {
		goto freepage_out
	}
	nFree = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+36)
	_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+36, nFree+uint32(1))
	if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_SECURE_DELETE) != 0 {
		/* If the secure_delete option is enabled, then
		 ** always fully overwrite deleted information with zeros.
		 */
		if v2 = !(**(**uintptr)(__ccgo_up(bp + 4)) != 0); v2 {
			v1 = _btreeGetPage(tls, pBt, iPage, bp+4, 0)
			**(**int32)(__ccgo_up(bp + 8)) = v1
		}
		if v4 = v2 && v1 != 0; !v4 {
			v3 = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage)
			**(**int32)(__ccgo_up(bp + 8)) = v3
		}
		if v4 || v3 != 0 {
			goto freepage_out
		}
		libc.Xmemset(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FaData, 0, (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpBt)).FpageSize)
	}
	/* If the database supports auto-vacuum, write an entry in the pointer-map
	 ** to indicate that the page is free.
	 */
	if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
		_ptrmapPut(tls, pBt, iPage, uint8(PTRMAP_FREEPAGE), uint32(0), bp+8)
		if **(**int32)(__ccgo_up(bp + 8)) != 0 {
			goto freepage_out
		}
	}
	/* Now manipulate the actual database free-list structure. There are two
	 ** possibilities. If the free-list is currently empty, or if the first
	 ** trunk page in the free-list is full, then this page will become a
	 ** new free-list trunk page. Otherwise, it will become a leaf of the
	 ** first trunk page in the current free-list. This block tests if it
	 ** is possible to add the page as a new free-list leaf.
	 */
	if nFree != uint32(0) { /* Initial number of leaf cells on trunk page */
		iTrunk = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32)
		if iTrunk > _btreePagecount(tls, pBt) {
			**(**int32)(__ccgo_up(bp + 8)) = _sqlite3CorruptError(tls, int32(80122))
			goto freepage_out
		}
		**(**int32)(__ccgo_up(bp + 8)) = _btreeGetPage(tls, pBt, iTrunk, bp, 0)
		if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
			goto freepage_out
		}
		nLeaf = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+4)
		if nLeaf > (*TBtShared)(unsafe.Pointer(pBt)).FusableSize/uint32(4)-uint32(2) {
			**(**int32)(__ccgo_up(bp + 8)) = _sqlite3CorruptError(tls, int32(80133))
			goto freepage_out
		}
		if nLeaf < (*TBtShared)(unsafe.Pointer(pBt)).FusableSize/uint32(4)-uint32(8) {
			/* In this case there is room on the trunk page to insert the page
			 ** being freed as a new leaf.
			 **
			 ** Note that the trunk page is not really full until it contains
			 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
			 ** coded.  But due to a coding error in versions of SQLite prior to
			 ** 3.6.0, databases with freelist trunk pages holding more than
			 ** usableSize/4 - 8 entries will be reported as corrupt.  In order
			 ** to maintain backwards compatibility with older versions of SQLite,
			 ** we will continue to restrict the number of entries to usableSize/4 - 8
			 ** for now.  At some point in the future (once everyone has upgraded
			 ** to 3.6.0 or later) we should consider fixing the conditional above
			 ** to read "usableSize/4-2" instead of "usableSize/4-8".
			 **
			 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
			 ** avoid using the last six entries in the freelist trunk page array in
			 ** order that database files created by newer versions of SQLite can be
			 ** read by older versions of SQLite.
			 */
			**(**int32)(__ccgo_up(bp + 8)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
			if **(**int32)(__ccgo_up(bp + 8)) == SQLITE_OK {
				_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+4, nLeaf+uint32(1))
				_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData+uintptr(uint32(8)+nLeaf*uint32(4)), iPage)
				if **(**uintptr)(__ccgo_up(bp + 4)) != 0 && libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_SECURE_DELETE) == 0 {
					_sqlite3PagerDontWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage)
				}
				**(**int32)(__ccgo_up(bp + 8)) = _btreeSetHasContent(tls, pBt, iPage)
			}
			goto freepage_out
		}
	}
	/* If control flows to this point, then it was not possible to add the
	 ** the page being freed as a leaf page of the first trunk in the free-list.
	 ** Possibly because the free-list is empty, or possibly because the
	 ** first trunk in the free-list is full. Either way, the page being freed
	 ** will become the new first trunk page in the free-list.
	 */
	if v2 = **(**uintptr)(__ccgo_up(bp + 4)) == uintptr(0); v2 {
		v1 = _btreeGetPage(tls, pBt, iPage, bp+4, 0)
		**(**int32)(__ccgo_up(bp + 8)) = v1
	}
	if v2 && SQLITE_OK != v1 {
		goto freepage_out
	}
	**(**int32)(__ccgo_up(bp + 8)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FpDbPage)
	if **(**int32)(__ccgo_up(bp + 8)) != SQLITE_OK {
		goto freepage_out
	}
	_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FaData, iTrunk)
	_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FaData+4, uint32(0))
	_sqlite3Put4byte(tls, (*TMemPage)(unsafe.Pointer(pPage1)).FaData+32, iPage)
	goto freepage_out
freepage_out:
	;
	if **(**uintptr)(__ccgo_up(bp + 4)) != 0 {
		(*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 4)))).FisInit = uint8(0)
	}
	_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 4)))
	_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
	return **(**int32)(__ccgo_up(bp + 8))
}

// C documentation
//
//	/*
//	** Return a section of the pPage->aData to the freelist.
//	** The first byte of the new free block is pPage->aData[iStart]
//	** and the size of the block is iSize bytes.
//	**
//	** Adjacent freeblocks are coalesced.
//	**
//	** Even though the freeblock list was checked by btreeComputeFreeSpace(),
//	** that routine will not detect overlap between cells or freeblocks.  Nor
//	** does it detect cells or freeblocks that encroach into the reserved bytes
//	** at the end of the page.  So do additional corruption checks inside this
//	** routine and return SQLITE_CORRUPT if any problems are found.
//	*/
func _freeSpace(tls *libc.TLS, pPage uintptr, iStart int32, iSize int32) (r int32) {
	var data, pTmp, v2 uintptr
	var hdr Tu8
	var iEnd, iFreeBlk, iOrigSize, iPtr, iPtrEnd, nFrag, x, v1 int32
	_, _, _, _, _, _, _, _, _, _, _, _ = data, hdr, iEnd, iFreeBlk, iOrigSize, iPtr, iPtrEnd, nFrag, pTmp, x, v1, v2 /* Page header size.  0 or 100 */
	nFrag = 0                                                                                                        /* Reduction in fragmentation */
	iOrigSize = iSize                                                                                                /* Offset to cell content area */
	iEnd = iStart + iSize                                                                                            /* First byte past the iStart buffer */
	data = (*TMemPage)(unsafe.Pointer(pPage)).FaData                                                                 /* Temporary ptr into data[] */
	/* Minimum cell size is 4 */
	/* The list of freeblocks must be in ascending order.  Find the
	 ** spot on the list where iStart should be inserted.
	 */
	hdr = (*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset
	iPtr = libc.Int32FromUint8(hdr) + int32(1)
	if libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr+int32(1))))) == 0 && libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr)))) == 0 {
		iFreeBlk = 0 /* Shortcut for the case when the freelist is empty */
	} else {
		for {
			v1 = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr))))<<libc.Int32FromInt32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr) + 1)))
			iFreeBlk = v1
			if !(v1 < iStart) {
				break
			}
			if iFreeBlk <= iPtr {
				if iFreeBlk == 0 {
					break
				} /* TH3: corrupt082.100 */
				return _sqlite3CorruptError(tls, int32(75174))
			}
			iPtr = iFreeBlk
		}
		if iFreeBlk > libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize)-int32(4) { /* TH3: corrupt081.100 */
			return _sqlite3CorruptError(tls, int32(75179))
		}
		/* At this point:
		 **    iFreeBlk:   First freeblock after iStart, or zero if none
		 **    iPtr:       The address of a pointer to iFreeBlk
		 **
		 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
		 */
		if iFreeBlk != 0 && iEnd+int32(3) >= iFreeBlk {
			nFrag = iFreeBlk - iEnd
			if iEnd > iFreeBlk {
				return _sqlite3CorruptError(tls, int32(75191))
			}
			iEnd = iFreeBlk + (libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFreeBlk+int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFreeBlk+int32(2)) + 1))))
			if iEnd > libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FusableSize) {
				return _sqlite3CorruptError(tls, int32(75194))
			}
			iSize = iEnd - iStart
			iFreeBlk = libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFreeBlk))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iFreeBlk) + 1)))
		}
		/* If iPtr is another freeblock (that is, if iPtr is not the freelist
		 ** pointer in the page header) then check to see if iStart should be
		 ** coalesced onto the end of iPtr.
		 */
		if iPtr > libc.Int32FromUint8(hdr)+int32(1) {
			iPtrEnd = iPtr + (libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr+int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(iPtr+int32(2)) + 1))))
			if iPtrEnd+int32(3) >= iStart {
				if iPtrEnd > iStart {
					return _sqlite3CorruptError(tls, int32(75207))
				}
				nFrag = nFrag + (iStart - iPtrEnd)
				iSize = iEnd - iPtr
				iStart = iPtr
			}
		}
		if nFrag > libc.Int32FromUint8(**(**uint8)(__ccgo_up(data + uintptr(libc.Int32FromUint8(hdr)+int32(7))))) {
			return _sqlite3CorruptError(tls, int32(75213))
		}
		v2 = data + uintptr(libc.Int32FromUint8(hdr)+int32(7))
		*(*uint8)(unsafe.Pointer(v2)) = uint8(int32(*(*uint8)(unsafe.Pointer(v2))) - libc.Int32FromUint8(libc.Uint8FromInt32(nFrag)))
	}
	pTmp = data + uintptr(libc.Int32FromUint8(hdr)+int32(5))
	x = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp + 1)))
	if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FbtsFlags)&int32(BTS_FAST_SECURE) != 0 {
		/* Overwrite deleted information with zeros when the secure_delete
		 ** option is enabled */
		libc.Xmemset(tls, data+uintptr(iStart), 0, libc.Uint32FromInt32(iSize))
	}
	if iStart <= x {
		/* The new freeblock is at the beginning of the cell content area,
		 ** so just extend the cell content area rather than create another
		 ** freelist entry */
		if iStart < x {
			return _sqlite3CorruptError(tls, int32(75227))
		}
		if iPtr != libc.Int32FromUint8(hdr)+int32(1) {
			return _sqlite3CorruptError(tls, int32(75228))
		}
		**(**uint8)(__ccgo_up(data + uintptr(libc.Int32FromUint8(hdr)+int32(1)))) = libc.Uint8FromInt32(iFreeBlk >> libc.Int32FromInt32(8))
		**(**uint8)(__ccgo_up(data + uintptr(libc.Int32FromUint8(hdr)+int32(1)) + 1)) = libc.Uint8FromInt32(iFreeBlk)
		**(**uint8)(__ccgo_up(data + uintptr(libc.Int32FromUint8(hdr)+int32(5)))) = libc.Uint8FromInt32(iEnd >> libc.Int32FromInt32(8))
		**(**uint8)(__ccgo_up(data + uintptr(libc.Int32FromUint8(hdr)+int32(5)) + 1)) = libc.Uint8FromInt32(iEnd)
	} else {
		/* Insert the new freeblock into the freelist */
		**(**uint8)(__ccgo_up(data + uintptr(iPtr))) = libc.Uint8FromInt32(iStart >> libc.Int32FromInt32(8))
		**(**uint8)(__ccgo_up(data + uintptr(iPtr) + 1)) = libc.Uint8FromInt32(iStart)
		**(**uint8)(__ccgo_up(data + uintptr(iStart))) = libc.Uint8FromInt32(iFreeBlk >> libc.Int32FromInt32(8))
		**(**uint8)(__ccgo_up(data + uintptr(iStart) + 1)) = libc.Uint8FromInt32(iFreeBlk)
		**(**uint8)(__ccgo_up(data + uintptr(iStart+int32(2)))) = libc.Uint8FromInt32(libc.Int32FromUint16(libc.Uint16FromInt32(iSize)) >> libc.Int32FromInt32(8))
		**(**uint8)(__ccgo_up(data + uintptr(iStart+int32(2)) + 1)) = uint8(libc.Uint16FromInt32(iSize))
	}
	**(**int32)(__ccgo_up(pPage + 20)) += iOrigSize
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
//	** be implemented as a co-routine.  The i-th entry is guaranteed to be
//	** a subquery.
//	**
//	** The subquery is implemented as a co-routine if all of the following are
//	** true:
//	**
//	**    (1)  The subquery will likely be implemented in the outer loop of
//	**         the query.  This will be the case if any one of the following
//	**         conditions hold:
//	**         (a)  The subquery is the only term in the FROM clause
//	**         (b)  The subquery is the left-most term and a CROSS JOIN or similar
//	**              requires it to be the outer loop
//	**         (c)  All of the following are true:
//	**                (i) The subquery is the left-most subquery in the FROM clause
//	**               (ii) There is nothing that would prevent the subquery from
//	**                    being used as the outer loop if the sqlite3WhereBegin()
//	**                    routine nominates it to that position.
//	**              (iii) The query is not a UPDATE ... FROM
//	**    (2)  The subquery is not a CTE that should be materialized because
//	**         (a) the AS MATERIALIZED keyword is used, or
//	**         (b) the CTE is used multiple times and does not have the
//	**             NOT MATERIALIZED keyword
//	**    (3)  The subquery is not part of a left operand for a RIGHT JOIN
//	**    (4)  The SQLITE_Coroutine optimization disable flag is not set
//	**    (5)  The subquery is not self-joined
//	*/
func _fromClauseTermCanBeCoroutine(tls *libc.TLS, pParse uintptr, pTabList uintptr, i int32, selFlags int32) (r int32) {
	var pCteUse, pItem uintptr
	_, _ = pCteUse, pItem
	pItem = pTabList + 8 + uintptr(i)*48
	if int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x200>>9) != 0 {
		pCteUse = *(*uintptr)(unsafe.Pointer(pItem + 36))
		if libc.Int32FromUint8((*TCteUse)(unsafe.Pointer(pCteUse)).FeM10d) == M10d_Yes {
			return 0
		} /* (2a) */
		if (*TCteUse)(unsafe.Pointer(pCteUse)).FnUse >= int32(2) && libc.Int32FromUint8((*TCteUse)(unsafe.Pointer(pCteUse)).FeM10d) != int32(M10d_No) {
			return 0
		} /* (2b) */
	}
	if libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(pTabList + 8))).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
		return 0
	} /* (3)  */
	if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_Coroutines)) != uint32(0) {
		return 0
	} /* (4)  */
	if _isSelfJoinView(tls, pTabList, pItem, i+int32(1), (*TSrcList)(unsafe.Pointer(pTabList)).FnSrc) != uintptr(0) {
		return 0 /* (5) */
	}
	if i == 0 {
		if (*TSrcList)(unsafe.Pointer(pTabList)).FnSrc == int32(1) {
			return int32(1)
		} /* (1a) */
		if libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(pTabList + 8 + 1*48))).Ffg.Fjointype)&int32(JT_CROSS) != 0 {
			return int32(1)
		} /* (1b) */
		if selFlags&int32(SF_UpdateFrom) != 0 {
			return 0
		} /* (1c-iii) */
		return int32(1)
	}
	if selFlags&int32(SF_UpdateFrom) != 0 {
		return 0
	} /* (1c-iii) */
	for int32(1) != 0 {
		if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pItem)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_OUTER)|libc.Int32FromInt32(JT_CROSS)) != 0 {
			return 0
		} /* (1c-ii) */
		if i == 0 {
			break
		}
		i = i - 1
		pItem -= 48
		if int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x4>>2) != 0 {
			return 0
		} /* (1c-i) */
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** The xColumnLocale() API.
//	*/
func _fts5ApiColumnLocale(tls *libc.TLS, pCtx uintptr, iCol int32, pzLocale uintptr, pnLocale uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pConfig, pCsr uintptr
	var rc int32
	var _ /* nDummy at bp+4 */ int32
	var _ /* zDummy at bp+0 */ uintptr
	_, _, _ = pConfig, pCsr, rc
	rc = SQLITE_OK
	pCsr = pCtx
	pConfig = (*TFts5Table)(unsafe.Pointer((*TFts5Cursor)(unsafe.Pointer(pCsr)).Fbase.FpVtab)).FpConfig
	**(**uintptr)(__ccgo_up(pzLocale)) = uintptr(0)
	**(**int32)(__ccgo_up(pnLocale)) = 0
	if iCol < 0 || iCol >= (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol {
		rc = int32(SQLITE_RANGE)
	} else {
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Config)(unsafe.Pointer(pConfig)).FabUnindexed + uintptr(iCol)))) == 0 && 0 == _fts5IsContentless(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).Fbase.FpVtab, int32(1)) && (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 {
			rc = _fts5SeekCursor(tls, pCsr, 0)
			if rc == SQLITE_OK {
				**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
				**(**int32)(__ccgo_up(bp + 4)) = 0
				rc = _fts5TextFromStmt(tls, pConfig, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpStmt, iCol, bp, bp+4)
				if rc == SQLITE_OK {
					**(**uintptr)(__ccgo_up(pzLocale)) = (*TFts5Config)(unsafe.Pointer(pConfig)).Ft.FpLocale
					**(**int32)(__ccgo_up(pnLocale)) = (*TFts5Config)(unsafe.Pointer(pConfig)).Ft.FnLocale
				}
				_sqlite3Fts5ClearLocale(tls, pConfig)
			}
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Implementation of bm25() function.
//	*/
func _fts5Bm25Function(tls *libc.TLS, pApi uintptr, pFts uintptr, pCtx uintptr, nVal int32, apVal uintptr) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var D, b, k1, score, w, v2 float64
	var aFreq uintptr
	var i, rc int32
	var _ /* ic at bp+12 */ int32
	var _ /* io at bp+16 */ int32
	var _ /* ip at bp+8 */ int32
	var _ /* nInst at bp+4 */ int32
	var _ /* nTok at bp+20 */ int32
	var _ /* pData at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _ = D, aFreq, b, i, k1, rc, score, w, v2
	k1 = float64(1.2)                  /* Constant "k1" from BM25 formula */
	b = float64(0.75)                  /* Error code */
	score = float64(0)                 /* Iterator variable */
	**(**int32)(__ccgo_up(bp + 4)) = 0 /* Value returned by xInstCount() */
	D = float64(0)                     /* Total number of tokens in row */
	aFreq = uintptr(0)                 /* Array of phrase freq. for current row */
	/* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
	 ** for each phrase in the query for the current row. */
	rc = _fts5Bm25GetData(tls, pApi, pFts, bp)
	if rc == SQLITE_OK {
		aFreq = (*TFts5Bm25Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaFreq
		libc.Xmemset(tls, aFreq, 0, uint32(8)*libc.Uint32FromInt32((*TFts5Bm25Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnPhrase))
		rc = (*(*func(*libc.TLS, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*TFts5ExtensionApi)(unsafe.Pointer(pApi)).FxInstCount})))(tls, pFts, bp+4)
	}
	i = 0
	for {
		if !(rc == SQLITE_OK && i < **(**int32)(__ccgo_up(bp + 4))) {
			break
		}
		rc = (*(*func(*libc.TLS, uintptr, int32, uintptr, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*TFts5ExtensionApi)(unsafe.Pointer(pApi)).FxInst})))(tls, pFts, i, bp+8, bp+12, bp+16)
		if rc == SQLITE_OK {
			if nVal > **(**int32)(__ccgo_up(bp + 12)) {
				v2 = Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(apVal + uintptr(**(**int32)(__ccgo_up(bp + 12)))*4)))
			} else {
				v2 = float64(1)
			}
			w = v2
			**(**float64)(__ccgo_up(aFreq + uintptr(**(**int32)(__ccgo_up(bp + 8)))*8)) += w
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	/* Figure out the total size of the current row in tokens. */
	if rc == SQLITE_OK {
		rc = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*TFts5ExtensionApi)(unsafe.Pointer(pApi)).FxColumnSize})))(tls, pFts, -int32(1), bp+20)
		D = float64(**(**int32)(__ccgo_up(bp + 20)))
	}
	/* Determine and return the BM25 score for the current row. Or, if an
	 ** error has occurred, throw an exception. */
	if rc == SQLITE_OK {
		i = 0
		for {
			if !(i < (*TFts5Bm25Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnPhrase) {
				break
			}
			score = score + float64(**(**float64)(__ccgo_up((*TFts5Bm25Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaIDF + uintptr(i)*8))*(float64(**(**float64)(__ccgo_up(aFreq + uintptr(i)*8))*(k1+libc.Float64FromFloat64(1)))/(**(**float64)(__ccgo_up(aFreq + uintptr(i)*8))+float64(k1*(libc.Float64FromInt32(1)-b+float64(b*D)/(*TFts5Bm25Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Favgdl)))))
			goto _3
		_3:
			;
			i = i + 1
		}
		Xsqlite3_result_double(tls, pCtx, float64(-libc.Float64FromFloat64(1)*score))
	} else {
		Xsqlite3_result_error_code(tls, pCtx, rc)
	}
}

// C documentation
//
//	/*
//	** Compare the contents of the two buffers using memcmp(). If one buffer
//	** is a prefix of the other, it is considered the lesser.
//	**
//	** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
//	** +ve if pRight is smaller than pLeft. In other words:
//	**
//	**     res = *pLeft - *pRight
//	*/
func _fts5BufferCompare(tls *libc.TLS, pLeft uintptr, pRight uintptr) (r int32) {
	var nCmp, res, v1 int32
	_, _, _ = nCmp, res, v1
	if (*TFts5Buffer)(unsafe.Pointer(pLeft)).Fn < (*TFts5Buffer)(unsafe.Pointer(pRight)).Fn {
		v1 = (*TFts5Buffer)(unsafe.Pointer(pLeft)).Fn
	} else {
		v1 = (*TFts5Buffer)(unsafe.Pointer(pRight)).Fn
	}
	nCmp = v1
	if nCmp <= 0 {
		v1 = 0
	} else {
		v1 = libc.Xmemcmp(tls, (*TFts5Buffer)(unsafe.Pointer(pLeft)).Fp, (*TFts5Buffer)(unsafe.Pointer(pRight)).Fp, libc.Uint32FromInt32(nCmp))
	}
	res = v1
	if res == 0 {
		v1 = (*TFts5Buffer)(unsafe.Pointer(pLeft)).Fn - (*TFts5Buffer)(unsafe.Pointer(pRight)).Fn
	} else {
		v1 = res
	}
	return v1
}

// C documentation
//
//	/*
//	** If argument pOrig is NULL, or if (*pRc) is set to anything other than
//	** SQLITE_OK when this function is called, NULL is returned.
//	**
//	** Otherwise, a copy of (*pOrig) is made into memory obtained from
//	** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
//	** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
//	*/
func _fts5CloneColset(tls *libc.TLS, pRc uintptr, pOrig uintptr) (r uintptr) {
	var nByte Tsqlite3_int64
	var pRet uintptr
	_, _ = nByte, pRet
	if pOrig != 0 {
		nByte = libc.Int64FromUint32(libc.Uint32FromInt64(8) * libc.Uint32FromInt32(((*TFts5Colset)(unsafe.Pointer(pOrig)).FnCol+libc.Int32FromInt32(2))/libc.Int32FromInt32(2)))
		pRet = _sqlite3Fts5MallocZero(tls, pRc, nByte)
		if pRet != 0 {
			libc.Xmemcpy(tls, pRet, pOrig, libc.Uint32FromInt64(nByte))
		}
	} else {
		pRet = uintptr(0)
	}
	return pRet
}

func _fts5ConfigSetEnum(tls *libc.TLS, aEnum uintptr, zEnum uintptr, peVal uintptr) (r int32) {
	var i, iVal, nEnum, v2 int32
	_, _, _, _ = i, iVal, nEnum, v2
	nEnum = libc.Int32FromUint32(libc.Xstrlen(tls, zEnum))
	iVal = -int32(1)
	i = 0
	for {
		if !((**(**TFts5Enum)(__ccgo_up(aEnum + uintptr(i)*8))).FzName != 0) {
			break
		}
		if Xsqlite3_strnicmp(tls, (**(**TFts5Enum)(__ccgo_up(aEnum + uintptr(i)*8))).FzName, zEnum, nEnum) == 0 {
			if iVal >= 0 {
				return int32(SQLITE_ERROR)
			}
			iVal = (**(**TFts5Enum)(__ccgo_up(aEnum + uintptr(i)*8))).FeVal
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	**(**int32)(__ccgo_up(peVal)) = iVal
	if iVal < 0 {
		v2 = int32(SQLITE_ERROR)
	} else {
		v2 = SQLITE_OK
	}
	return v2
}

// C documentation
//
//	/*
//	** Register a new auxiliary function with global context pGlobal.
//	*/
func _fts5CreateAux(tls *libc.TLS, pApi uintptr, zName uintptr, pUserData uintptr, __ccgo_fp_xFunc Tfts5_extension_function, __ccgo_fp_xDestroy uintptr) (r int32) {
	var nByte, nName Tsqlite3_int64
	var pAux, pGlobal uintptr
	var rc int32
	_, _, _, _, _ = nByte, nName, pAux, pGlobal, rc
	pGlobal = pApi
	rc = Xsqlite3_overload_function(tls, (*TFts5Global)(unsafe.Pointer(pGlobal)).Fdb, zName, -int32(1))
	if rc == SQLITE_OK { /* Bytes of space to allocate */
		nName = libc.Int64FromUint32(libc.Xstrlen(tls, zName) + uint32(1))
		nByte = int64(24) + nName
		pAux = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if pAux != 0 {
			libc.Xmemset(tls, pAux, 0, libc.Uint32FromInt64(nByte))
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FzFunc = pAux + 1*24
			libc.Xmemcpy(tls, (*TFts5Auxiliary)(unsafe.Pointer(pAux)).FzFunc, zName, libc.Uint32FromInt64(nName))
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FpGlobal = pGlobal
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FpUserData = pUserData
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FxFunc = __ccgo_fp_xFunc
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FxDestroy = __ccgo_fp_xDestroy
			(*TFts5Auxiliary)(unsafe.Pointer(pAux)).FpNext = (*TFts5Global)(unsafe.Pointer(pGlobal)).FpAux
			(*TFts5Global)(unsafe.Pointer(pGlobal)).FpAux = pAux
		} else {
			rc = int32(SQLITE_NOMEM)
		}
	}
	return rc
}

func _fts5ExprAssignXNext(tls *libc.TLS, pNode uintptr) {
	var pNear uintptr
	_ = pNear
	switch (*TFts5ExprNode)(unsafe.Pointer(pNode)).FeType {
	case int32(FTS5_STRING):
		pNear = (*TFts5ExprNode)(unsafe.Pointer(pNode)).FpNear
		if (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase == int32(1) && (*TFts5ExprPhrase)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pNear + 12)))).FnTerm == int32(1) && (*(*TFts5ExprTerm)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pNear + 12)) + 20))).FpSynonym == uintptr(0) && libc.Int32FromUint8((*(*TFts5ExprTerm)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pNear + 12)) + 20))).FbFirst) == 0 {
			(*TFts5ExprNode)(unsafe.Pointer(pNode)).FeType = int32(FTS5_TERM)
			(*TFts5ExprNode)(unsafe.Pointer(pNode)).FxNext = __ccgo_fp(_fts5ExprNodeNext_TERM)
		} else {
			(*TFts5ExprNode)(unsafe.Pointer(pNode)).FxNext = __ccgo_fp(_fts5ExprNodeNext_STRING)
		}
	case int32(FTS5_OR):
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FxNext = __ccgo_fp(_fts5ExprNodeNext_OR)
	case int32(FTS5_AND):
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FxNext = __ccgo_fp(_fts5ExprNodeNext_AND)
	default:
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FxNext = __ccgo_fp(_fts5ExprNodeNext_NOT)
		break
	}
}

// C documentation
//
//	/*
//	** Initialize all term iterators in the pNear object. If any term is found
//	** to match no documents at all, return immediately without initializing any
//	** further iterators.
//	**
//	** If an error occurs, return an SQLite error code. Otherwise, return
//	** SQLITE_OK. It is not considered an error if some term matches zero
//	** documents.
//	*/
func _fts5ExprNearInitAll(tls *libc.TLS, pExpr uintptr, pNode uintptr) (r int32) {
	var bHit, i, j, rc, v4, v5 int32
	var p, pNear, pPhrase, pTerm uintptr
	_, _, _, _, _, _, _, _, _, _ = bHit, i, j, p, pNear, pPhrase, pTerm, rc, v4, v5
	pNear = (*TFts5ExprNode)(unsafe.Pointer(pNode)).FpNear
	i = 0
	for {
		if !(i < (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase) {
			break
		}
		pPhrase = *(*uintptr)(unsafe.Pointer(pNear + 12 + uintptr(i)*4))
		if (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm == 0 {
			(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = int32(1)
			return SQLITE_OK
		} else {
			j = 0
			for {
				if !(j < (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm) {
					break
				}
				pTerm = pPhrase + 20 + uintptr(j)*24
				bHit = 0
				p = pTerm
				for {
					if !(p != 0) {
						break
					}
					if (*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter != 0 {
						_sqlite3Fts5IterClose(tls, (*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)
						(*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter = uintptr(0)
					}
					if (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FbPrefix != 0 {
						v4 = int32(FTS5INDEX_QUERY_PREFIX)
					} else {
						v4 = 0
					}
					if (*TFts5Expr)(unsafe.Pointer(pExpr)).FbDesc != 0 {
						v5 = int32(FTS5INDEX_QUERY_DESC)
					} else {
						v5 = 0
					}
					rc = _sqlite3Fts5IndexQuery(tls, (*TFts5Expr)(unsafe.Pointer(pExpr)).FpIndex, (*TFts5ExprTerm)(unsafe.Pointer(p)).FpTerm, (*TFts5ExprTerm)(unsafe.Pointer(p)).FnQueryTerm, v4|v5, (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FpColset, p+16)
					if rc != SQLITE_OK {
						return rc
					}
					if 0 == libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)).FbEof) {
						bHit = int32(1)
					}
					goto _3
				_3:
					;
					p = (*TFts5ExprTerm)(unsafe.Pointer(p)).FpSynonym
				}
				if bHit == 0 {
					(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = int32(1)
					return SQLITE_OK
				}
				goto _2
			_2:
				;
				j = j + 1
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = 0
	return SQLITE_OK
}

func _fts5ExprNearTest(tls *libc.TLS, pRc uintptr, pExpr uintptr, pNode uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i int32
	var pIter, pIter1, pNear, pPhrase, pPhrase1, pTerm uintptr
	var _ /* bMatch at bp+4 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _ = i, pIter, pIter1, pNear, pPhrase, pPhrase1, pTerm
	pNear = (*TFts5ExprNode)(unsafe.Pointer(pNode)).FpNear
	**(**int32)(__ccgo_up(bp)) = **(**int32)(__ccgo_up(pRc))
	if (*TFts5Config)(unsafe.Pointer((*TFts5Expr)(unsafe.Pointer(pExpr)).FpConfig)).FeDetail != FTS5_DETAIL_FULL {
		pPhrase = *(*uintptr)(unsafe.Pointer(pNear + 12))
		(*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).Fposlist.Fn = 0
		pTerm = pPhrase + 20
		for {
			if !(pTerm != 0) {
				break
			}
			pIter = (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpIter
			if libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer(pIter)).FbEof) == 0 {
				if (*TFts5IndexIter)(unsafe.Pointer(pIter)).FiRowid == (*TFts5ExprNode)(unsafe.Pointer(pNode)).FiRowid && (*TFts5IndexIter)(unsafe.Pointer(pIter)).FnData > 0 {
					(*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).Fposlist.Fn = int32(1)
				}
			}
			goto _1
		_1:
			;
			pTerm = (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpSynonym
		}
		return (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).Fposlist.Fn
	} else {
		/* Check that each phrase in the nearset matches the current row.
		 ** Populate the pPhrase->poslist buffers at the same time. If any
		 ** phrase is not a match, break out of the loop early.  */
		i = 0
		for {
			if !(**(**int32)(__ccgo_up(bp)) == SQLITE_OK && i < (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase) {
				break
			}
			pPhrase1 = *(*uintptr)(unsafe.Pointer(pNear + 12 + uintptr(i)*4))
			if (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase1)).FnTerm > int32(1) || (*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase1 + 20))).FpSynonym != 0 || (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FpColset != 0 || (*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase1 + 20))).FbFirst != 0 {
				**(**int32)(__ccgo_up(bp + 4)) = 0
				**(**int32)(__ccgo_up(bp)) = _fts5ExprPhraseIsMatch(tls, pNode, pPhrase1, bp+4)
				if **(**int32)(__ccgo_up(bp + 4)) == 0 {
					break
				}
			} else {
				pIter1 = (*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase1 + 20))).FpIter
				_sqlite3Fts5BufferSet(tls, bp, pPhrase1+4, (*TFts5IndexIter)(unsafe.Pointer(pIter1)).FnData, (*TFts5IndexIter)(unsafe.Pointer(pIter1)).FpData)
			}
			goto _2
		_2:
			;
			i = i + 1
		}
		**(**int32)(__ccgo_up(pRc)) = **(**int32)(__ccgo_up(bp))
		if i == (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase && (i == int32(1) || _fts5ExprNearIsMatch(tls, pRc, pNear) != 0) {
			return int32(1)
		}
		return 0
	}
	return r
}

// C documentation
//
//	/*
//	** Advance the first term iterator in the first phrase of pNear. Set output
//	** variable *pbEof to true if it reaches EOF or if an error occurs.
//	**
//	** Return SQLITE_OK if successful, or an SQLite error code if an error
//	** occurs.
//	*/
func _fts5ExprNodeNext_STRING(tls *libc.TLS, pExpr uintptr, pNode uintptr, bFromValid int32, iFrom Ti64) (r int32) {
	var bEof, rc int32
	var iRowid, ii Ti64
	var p, pIter, pTerm uintptr
	_, _, _, _, _, _, _ = bEof, iRowid, ii, p, pIter, pTerm, rc
	pTerm = *(*uintptr)(unsafe.Pointer((*TFts5ExprNode)(unsafe.Pointer(pNode)).FpNear + 12)) + 20
	rc = SQLITE_OK
	(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbNomatch = 0
	if (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpSynonym != 0 {
		bEof = int32(1)
		/* Find the firstest rowid any synonym points to. */
		iRowid = _fts5ExprSynonymRowid(tls, pTerm, (*TFts5Expr)(unsafe.Pointer(pExpr)).FbDesc, uintptr(0))
		/* Advance each iterator that currently points to iRowid. Or, if iFrom
		 ** is valid - each iterator that points to a rowid before iFrom.  */
		p = pTerm
		for {
			if !(p != 0) {
				break
			}
			if libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)).FbEof) == 0 {
				ii = (*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)).FiRowid
				if ii == iRowid || bFromValid != 0 && ii != iFrom && libc.BoolInt32(ii > iFrom) == (*TFts5Expr)(unsafe.Pointer(pExpr)).FbDesc {
					if bFromValid != 0 {
						rc = _sqlite3Fts5IterNextFrom(tls, (*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter, iFrom)
					} else {
						rc = _sqlite3Fts5IterNext(tls, (*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)
					}
					if rc != SQLITE_OK {
						break
					}
					if libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter)).FbEof) == 0 {
						bEof = 0
					}
				} else {
					bEof = 0
				}
			}
			goto _1
		_1:
			;
			p = (*TFts5ExprTerm)(unsafe.Pointer(p)).FpSynonym
		}
		/* Set the EOF flag if either all synonym iterators are at EOF or an
		 ** error has occurred.  */
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = libc.BoolInt32(rc != 0 || bEof != 0)
	} else {
		pIter = (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpIter
		if bFromValid != 0 {
			rc = _sqlite3Fts5IterNextFrom(tls, pIter, iFrom)
		} else {
			rc = _sqlite3Fts5IterNext(tls, pIter)
		}
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = libc.BoolInt32(rc != 0 || (*TFts5IndexIter)(unsafe.Pointer(pIter)).FbEof != 0)
	}
	if (*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof == 0 {
		rc = _fts5ExprNodeTest_STRING(tls, pExpr, pNode)
	}
	return rc
}

// C documentation
//
//	/*
//	** xNext() method for a node of type FTS5_TERM.
//	*/
func _fts5ExprNodeNext_TERM(tls *libc.TLS, pExpr uintptr, pNode uintptr, bFromValid int32, iFrom Ti64) (r int32) {
	var pIter uintptr
	var rc int32
	_, _ = pIter, rc
	pIter = (*(*TFts5ExprTerm)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer((*TFts5ExprNode)(unsafe.Pointer(pNode)).FpNear + 12)) + 20))).FpIter
	if bFromValid != 0 {
		rc = _sqlite3Fts5IterNextFrom(tls, pIter, iFrom)
	} else {
		rc = _sqlite3Fts5IterNext(tls, pIter)
	}
	if rc == SQLITE_OK && libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer(pIter)).FbEof) == 0 {
		rc = _fts5ExprNodeTest_TERM(tls, pExpr, pNode)
	} else {
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof = int32(1)
		(*TFts5ExprNode)(unsafe.Pointer(pNode)).FbNomatch = 0
	}
	return rc
}

// C documentation
//
//	/*
//	** All individual term iterators in pPhrase are guaranteed to be valid and
//	** pointing to the same rowid when this function is called. This function
//	** checks if the current rowid really is a match, and if so populates
//	** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
//	** is set to true if this is really a match, or false otherwise.
//	**
//	** SQLITE_OK is returned if an error occurs, or an SQLite error code
//	** otherwise. It is not considered an error code if the current rowid is
//	** not a match.
//	*/
func _fts5ExprPhraseIsMatch(tls *libc.TLS, pNode uintptr, pPhrase uintptr, pbMatch uintptr) (r int32) {
	bp := tls.Alloc(128)
	defer tls.Free(128)
	var aIter, pPos, pTerm uintptr
	var bFirst, bFlag, bMatch, i, rc int32
	var iAdj, iPos Ti64
	var nByte Tsqlite3_int64
	var _ /* a at bp+108 */ uintptr
	var _ /* aStatic at bp+8 */ [4]TFts5PoslistReader
	var _ /* buf at bp+112 */ TFts5Buffer
	var _ /* n at bp+104 */ int32
	var _ /* writer at bp+0 */ TFts5PoslistWriter
	_, _, _, _, _, _, _, _, _, _, _ = aIter, bFirst, bFlag, bMatch, i, iAdj, iPos, nByte, pPos, pTerm, rc
	**(**TFts5PoslistWriter)(__ccgo_up(bp)) = TFts5PoslistWriter{}
	aIter = bp + 8
	rc = SQLITE_OK
	bFirst = libc.Int32FromUint8((*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase + 20))).FbFirst)
	_sqlite3Fts5BufferZero(tls, pPhrase+4)
	/* If the aStatic[] array is not large enough, allocate a large array
	 ** using sqlite3_malloc(). This approach could be improved upon. */
	if (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm > libc.Int32FromUint32(libc.Uint32FromInt64(96)/libc.Uint32FromInt64(24)) {
		nByte = libc.Int64FromUint32(uint32(24) * libc.Uint32FromInt32((*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm))
		aIter = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if !(aIter != 0) {
			return int32(SQLITE_NOMEM)
		}
	}
	libc.Xmemset(tls, aIter, 0, uint32(24)*libc.Uint32FromInt32((*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm))
	/* Initialize a term iterator for each term in the phrase */
	i = 0
	for {
		if !(i < (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm) {
			break
		}
		pTerm = pPhrase + 20 + uintptr(i)*24
		**(**int32)(__ccgo_up(bp + 104)) = 0
		bFlag = 0
		**(**uintptr)(__ccgo_up(bp + 108)) = uintptr(0)
		if (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpSynonym != 0 {
			**(**TFts5Buffer)(__ccgo_up(bp + 112)) = TFts5Buffer{}
			rc = _fts5ExprSynonymList(tls, pTerm, (*TFts5ExprNode)(unsafe.Pointer(pNode)).FiRowid, bp+112, bp+108, bp+104)
			if rc != 0 {
				Xsqlite3_free(tls, **(**uintptr)(__ccgo_up(bp + 108)))
				goto ismatch_out
			}
			if **(**uintptr)(__ccgo_up(bp + 108)) == (**(**TFts5Buffer)(__ccgo_up(bp + 112))).Fp {
				bFlag = int32(1)
			}
		} else {
			**(**uintptr)(__ccgo_up(bp + 108)) = (*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpIter)).FpData
			**(**int32)(__ccgo_up(bp + 104)) = (*TFts5IndexIter)(unsafe.Pointer((*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpIter)).FnData
		}
		_sqlite3Fts5PoslistReaderInit(tls, **(**uintptr)(__ccgo_up(bp + 108)), **(**int32)(__ccgo_up(bp + 104)), aIter+uintptr(i)*24)
		(**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FbFlag = libc.Uint8FromInt32(bFlag)
		if (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FbEof != 0 {
			goto ismatch_out
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	for int32(1) != 0 {
		iPos = (**(**TFts5PoslistReader)(__ccgo_up(aIter))).FiPos
		for cond := true; cond; cond = bMatch == 0 {
			bMatch = int32(1)
			i = 0
			for {
				if !(i < (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm) {
					break
				}
				pPos = aIter + uintptr(i)*24
				iAdj = iPos + int64(i)
				if (*TFts5PoslistReader)(unsafe.Pointer(pPos)).FiPos != iAdj {
					bMatch = 0
					for (*TFts5PoslistReader)(unsafe.Pointer(pPos)).FiPos < iAdj {
						if _sqlite3Fts5PoslistReaderNext(tls, pPos) != 0 {
							goto ismatch_out
						}
					}
					if (*TFts5PoslistReader)(unsafe.Pointer(pPos)).FiPos > iAdj {
						iPos = (*TFts5PoslistReader)(unsafe.Pointer(pPos)).FiPos - int64(i)
					}
				}
				goto _2
			_2:
				;
				i = i + 1
			}
		}
		/* Append position iPos to the output */
		if bFirst == 0 || int32(iPos&libc.Int64FromInt32(0x7FFFFFFF)) == 0 {
			rc = _sqlite3Fts5PoslistWriterAppend(tls, pPhrase+4, bp, iPos)
			if rc != SQLITE_OK {
				goto ismatch_out
			}
		}
		i = 0
		for {
			if !(i < (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm) {
				break
			}
			if _sqlite3Fts5PoslistReaderNext(tls, aIter+uintptr(i)*24) != 0 {
				goto ismatch_out
			}
			goto _3
		_3:
			;
			i = i + 1
		}
	}
	goto ismatch_out
ismatch_out:
	;
	**(**int32)(__ccgo_up(pbMatch)) = libc.BoolInt32((*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).Fposlist.Fn > 0)
	i = 0
	for {
		if !(i < (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm) {
			break
		}
		if (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FbFlag != 0 {
			Xsqlite3_free(tls, (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).Fa)
		}
		goto _4
	_4:
		;
		i = i + 1
	}
	if aIter != bp+8 {
		Xsqlite3_free(tls, aIter)
	}
	return rc
}

func _fts5ExprPopulatePoslistsCb(tls *libc.TLS, pCtx uintptr, tflags int32, pToken uintptr, nToken int32, iUnused1 int32, iUnused2 int32) (r int32) {
	var i, iCol, iTokOff, nQuery, rc int32
	var iRowid Ti64
	var p, pExpr, pT uintptr
	_, _, _, _, _, _, _, _, _ = i, iCol, iRowid, iTokOff, nQuery, p, pExpr, pT, rc
	p = pCtx
	pExpr = (*TFts5ExprCtx)(unsafe.Pointer(p)).FpExpr
	nQuery = nToken
	iRowid = (*TFts5ExprNode)(unsafe.Pointer((*TFts5Expr)(unsafe.Pointer(pExpr)).FpRoot)).FiRowid
	_ = iUnused1
	_ = iUnused2
	if nQuery > int32(FTS5_MAX_TOKEN_SIZE) {
		nQuery = int32(FTS5_MAX_TOKEN_SIZE)
	}
	if (*TFts5Config)(unsafe.Pointer((*TFts5Expr)(unsafe.Pointer(pExpr)).FpConfig)).FbTokendata != 0 {
		nQuery = _fts5QueryTerm(tls, pToken, nQuery)
	}
	if tflags&int32(FTS5_TOKEN_COLOCATED) == 0 {
		(*TFts5ExprCtx)(unsafe.Pointer(p)).FiOff = (*TFts5ExprCtx)(unsafe.Pointer(p)).FiOff + 1
	}
	i = 0
	for {
		if !(i < (*TFts5Expr)(unsafe.Pointer(pExpr)).FnPhrase) {
			break
		}
		if (**(**TFts5PoslistPopulator)(__ccgo_up((*TFts5ExprCtx)(unsafe.Pointer(p)).FaPopulator + uintptr(i)*16))).FbOk == 0 {
			goto _1
		}
		pT = **(**uintptr)(__ccgo_up((*TFts5Expr)(unsafe.Pointer(pExpr)).FapExprPhrase + uintptr(i)*4)) + 20
		for {
			if !(pT != 0) {
				break
			}
			if ((*TFts5ExprTerm)(unsafe.Pointer(pT)).FnQueryTerm == nQuery || (*TFts5ExprTerm)(unsafe.Pointer(pT)).FnQueryTerm < nQuery && (*TFts5ExprTerm)(unsafe.Pointer(pT)).FbPrefix != 0) && libc.Xmemcmp(tls, (*TFts5ExprTerm)(unsafe.Pointer(pT)).FpTerm, pToken, libc.Uint32FromInt32((*TFts5ExprTerm)(unsafe.Pointer(pT)).FnQueryTerm)) == 0 {
				rc = _sqlite3Fts5PoslistWriterAppend(tls, **(**uintptr)(__ccgo_up((*TFts5Expr)(unsafe.Pointer(pExpr)).FapExprPhrase + uintptr(i)*4))+4, (*TFts5ExprCtx)(unsafe.Pointer(p)).FaPopulator+uintptr(i)*16, (*TFts5ExprCtx)(unsafe.Pointer(p)).FiOff)
				if rc == SQLITE_OK && ((*TFts5Config)(unsafe.Pointer((*TFts5Expr)(unsafe.Pointer(pExpr)).FpConfig)).FbTokendata != 0 || (*TFts5ExprTerm)(unsafe.Pointer(pT)).FbPrefix != 0) {
					iCol = int32((*TFts5ExprCtx)(unsafe.Pointer(p)).FiOff >> int32(32))
					iTokOff = int32((*TFts5ExprCtx)(unsafe.Pointer(p)).FiOff & int64(0x7FFFFFFF))
					rc = _sqlite3Fts5IndexIterWriteTokendata(tls, (*TFts5ExprTerm)(unsafe.Pointer(pT)).FpIter, pToken, nToken, iRowid, iCol, iTokOff)
				}
				if rc != 0 {
					return rc
				}
				break
			}
			goto _2
		_2:
			;
			pT = (*TFts5ExprTerm)(unsafe.Pointer(pT)).FpSynonym
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Argument pTerm must be a synonym iterator.
//	*/
func _fts5ExprSynonymList(tls *libc.TLS, pTerm uintptr, iRowid Ti64, pBuf uintptr, pa uintptr, pn uintptr) (r int32) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var aIter, aNew, p, pIter uintptr
	var i, nAlloc, nIter, rc int32
	var iMin, iPrev Ti64
	var nByte Tsqlite3_int64
	var _ /* aStatic at bp+0 */ [4]TFts5PoslistReader
	var _ /* writer at bp+96 */ TFts5PoslistWriter
	_, _, _, _, _, _, _, _, _, _, _ = aIter, aNew, i, iMin, iPrev, nAlloc, nByte, nIter, p, pIter, rc
	aIter = bp
	nIter = 0
	nAlloc = int32(4)
	rc = SQLITE_OK
	p = pTerm
	for {
		if !(p != 0) {
			break
		}
		pIter = (*TFts5ExprTerm)(unsafe.Pointer(p)).FpIter
		if libc.Int32FromUint8((*TFts5IndexIter)(unsafe.Pointer(pIter)).FbEof) == 0 && (*TFts5IndexIter)(unsafe.Pointer(pIter)).FiRowid == iRowid {
			if (*TFts5IndexIter)(unsafe.Pointer(pIter)).FnData == 0 {
				goto _1
			}
			if nIter == nAlloc {
				nByte = libc.Int64FromUint32(uint32(24) * libc.Uint32FromInt32(nAlloc) * uint32(2))
				aNew = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
				if aNew == uintptr(0) {
					rc = int32(SQLITE_NOMEM)
					goto synonym_poslist_out
				}
				libc.Xmemcpy(tls, aNew, aIter, uint32(24)*libc.Uint32FromInt32(nIter))
				nAlloc = nAlloc * int32(2)
				if aIter != bp {
					Xsqlite3_free(tls, aIter)
				}
				aIter = aNew
			}
			_sqlite3Fts5PoslistReaderInit(tls, (*TFts5IndexIter)(unsafe.Pointer(pIter)).FpData, (*TFts5IndexIter)(unsafe.Pointer(pIter)).FnData, aIter+uintptr(nIter)*24)
			nIter = nIter + 1
		}
		goto _1
	_1:
		;
		p = (*TFts5ExprTerm)(unsafe.Pointer(p)).FpSynonym
	}
	if nIter == int32(1) {
		**(**uintptr)(__ccgo_up(pa)) = (**(**TFts5PoslistReader)(__ccgo_up(aIter))).Fa
		**(**int32)(__ccgo_up(pn)) = (**(**TFts5PoslistReader)(__ccgo_up(aIter))).Fn
	} else {
		**(**TFts5PoslistWriter)(__ccgo_up(bp + 96)) = TFts5PoslistWriter{}
		iPrev = int64(-int32(1))
		_sqlite3Fts5BufferZero(tls, pBuf)
		for int32(1) != 0 {
			iMin = libc.Int64FromUint32(0xffffffff) | libc.Int64FromInt32(0x7fffffff)<<libc.Int32FromInt32(32)
			i = 0
			for {
				if !(i < nIter) {
					break
				}
				if libc.Int32FromUint8((**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FbEof) == 0 {
					if (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FiPos == iPrev {
						if _sqlite3Fts5PoslistReaderNext(tls, aIter+uintptr(i)*24) != 0 {
							goto _2
						}
					}
					if (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FiPos < iMin {
						iMin = (**(**TFts5PoslistReader)(__ccgo_up(aIter + uintptr(i)*24))).FiPos
					}
				}
				goto _2
			_2:
				;
				i = i + 1
			}
			if iMin == libc.Int64FromUint32(0xffffffff)|libc.Int64FromInt32(0x7fffffff)<<libc.Int32FromInt32(32) || rc != SQLITE_OK {
				break
			}
			rc = _sqlite3Fts5PoslistWriterAppend(tls, pBuf, bp+96, iMin)
			iPrev = iMin
		}
		if rc == SQLITE_OK {
			**(**uintptr)(__ccgo_up(pa)) = (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp
			**(**int32)(__ccgo_up(pn)) = (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn
		}
	}
	goto synonym_poslist_out
synonym_poslist_out:
	;
	if aIter != bp {
		Xsqlite3_free(tls, aIter)
	}
	return rc
}

func _fts5HashAddPoslistSize(tls *libc.TLS, pHash uintptr, p uintptr, p2 uintptr) (r int32) {
	var nByte, nData, nPos, nRet, nSz, v2 int32
	var pPtr, v1 uintptr
	_, _, _, _, _, _, _, _ = nByte, nData, nPos, nRet, nSz, pPtr, v1, v2
	nRet = 0
	if (*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist != 0 {
		if p2 != 0 {
			v1 = p2
		} else {
			v1 = p
		}
		pPtr = v1
		nData = (*TFts5HashEntry)(unsafe.Pointer(p)).FnData
		if (*TFts5Hash)(unsafe.Pointer(pHash)).FeDetail == int32(FTS5_DETAIL_NONE) {
			if (*TFts5HashEntry)(unsafe.Pointer(p)).FbDel != 0 {
				v2 = nData
				nData = nData + 1
				**(**Tu8)(__ccgo_up(pPtr + uintptr(v2))) = uint8(0x00)
				if (*TFts5HashEntry)(unsafe.Pointer(p)).FbContent != 0 {
					v2 = nData
					nData = nData + 1
					**(**Tu8)(__ccgo_up(pPtr + uintptr(v2))) = uint8(0x00)
				}
			}
		} else {
			nSz = nData - (*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist - int32(1)             /* Size in bytes */
			nPos = nSz*int32(2) + libc.Int32FromUint8((*TFts5HashEntry)(unsafe.Pointer(p)).FbDel) /* Value of nPos field */
			if nPos <= int32(127) {
				**(**Tu8)(__ccgo_up(pPtr + uintptr((*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist))) = libc.Uint8FromInt32(nPos)
			} else {
				nByte = _sqlite3Fts5GetVarintLen(tls, libc.Uint32FromInt32(nPos))
				libc.Xmemmove(tls, pPtr+uintptr((*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist+nByte), pPtr+uintptr((*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist+int32(1)), libc.Uint32FromInt32(nSz))
				_sqlite3Fts5PutVarint(tls, pPtr+uintptr((*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist), libc.Uint64FromInt32(nPos))
				nData = nData + (nByte - int32(1))
			}
		}
		nRet = nData - (*TFts5HashEntry)(unsafe.Pointer(p)).FnData
		if p2 == uintptr(0) {
			(*TFts5HashEntry)(unsafe.Pointer(p)).FiSzPoslist = 0
			(*TFts5HashEntry)(unsafe.Pointer(p)).FbDel = uint8(0)
			(*TFts5HashEntry)(unsafe.Pointer(p)).FbContent = uint8(0)
			(*TFts5HashEntry)(unsafe.Pointer(p)).FnData = nData
		}
	}
	return nRet
}

// C documentation
//
//	/*
//	** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
//	** each sorted in key order. This function merges the two lists into a
//	** single list and returns a pointer to its first element.
//	*/
func _fts5HashEntryMerge(tls *libc.TLS, pLeft uintptr, pRight uintptr) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var cmp, nMin, v1 int32
	var p1, p2, ppOut, zKey1, zKey2 uintptr
	var _ /* pRet at bp+0 */ uintptr
	_, _, _, _, _, _, _, _ = cmp, nMin, p1, p2, ppOut, zKey1, zKey2, v1
	p1 = pLeft
	p2 = pRight
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	ppOut = bp
	for p1 != 0 || p2 != 0 {
		if p1 == uintptr(0) {
			**(**uintptr)(__ccgo_up(ppOut)) = p2
			p2 = uintptr(0)
		} else {
			if p2 == uintptr(0) {
				**(**uintptr)(__ccgo_up(ppOut)) = p1
				p1 = uintptr(0)
			} else {
				zKey1 = p1 + 1*40
				zKey2 = p2 + 1*40
				if (*TFts5HashEntry)(unsafe.Pointer(p1)).FnKey < (*TFts5HashEntry)(unsafe.Pointer(p2)).FnKey {
					v1 = (*TFts5HashEntry)(unsafe.Pointer(p1)).FnKey
				} else {
					v1 = (*TFts5HashEntry)(unsafe.Pointer(p2)).FnKey
				}
				nMin = v1
				cmp = libc.Xmemcmp(tls, zKey1, zKey2, libc.Uint32FromInt32(nMin))
				if cmp == 0 {
					cmp = (*TFts5HashEntry)(unsafe.Pointer(p1)).FnKey - (*TFts5HashEntry)(unsafe.Pointer(p2)).FnKey
				}
				if cmp > 0 {
					/* p2 is smaller */
					**(**uintptr)(__ccgo_up(ppOut)) = p2
					ppOut = p2 + 4
					p2 = (*TFts5HashEntry)(unsafe.Pointer(p2)).FpScanNext
				} else {
					/* p1 is smaller */
					**(**uintptr)(__ccgo_up(ppOut)) = p1
					ppOut = p1 + 4
					p1 = (*TFts5HashEntry)(unsafe.Pointer(p1)).FpScanNext
				}
				**(**uintptr)(__ccgo_up(ppOut)) = uintptr(0)
			}
		}
	}
	return **(**uintptr)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Link all tokens from hash table iHash into a list in sorted order. The
//	** tokens are not removed from the hash table.
//	*/
func _fts5HashEntrySort(tls *libc.TLS, pHash uintptr, pTerm uintptr, nTerm int32, ppSorted uintptr) (r int32) {
	var ap, pEntry, pIter, pList uintptr
	var i, iSlot, nMergeSlot int32
	_, _, _, _, _, _, _ = ap, i, iSlot, nMergeSlot, pEntry, pIter, pList
	nMergeSlot = int32(32)
	**(**uintptr)(__ccgo_up(ppSorted)) = uintptr(0)
	ap = Xsqlite3_malloc64(tls, uint64(uint32(4)*libc.Uint32FromInt32(nMergeSlot)))
	if !(ap != 0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, ap, 0, uint32(4)*libc.Uint32FromInt32(nMergeSlot))
	iSlot = 0
	for {
		if !(iSlot < (*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot) {
			break
		}
		pIter = **(**uintptr)(__ccgo_up((*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot + uintptr(iSlot)*4))
		for {
			if !(pIter != 0) {
				break
			}
			if pTerm == uintptr(0) || (*TFts5HashEntry)(unsafe.Pointer(pIter)).FnKey >= nTerm && 0 == libc.Xmemcmp(tls, pIter+1*40, pTerm, libc.Uint32FromInt32(nTerm)) {
				pEntry = pIter
				(*TFts5HashEntry)(unsafe.Pointer(pEntry)).FpScanNext = uintptr(0)
				i = 0
				for {
					if !(**(**uintptr)(__ccgo_up(ap + uintptr(i)*4)) != 0) {
						break
					}
					pEntry = _fts5HashEntryMerge(tls, pEntry, **(**uintptr)(__ccgo_up(ap + uintptr(i)*4)))
					**(**uintptr)(__ccgo_up(ap + uintptr(i)*4)) = uintptr(0)
					goto _3
				_3:
					;
					i = i + 1
				}
				**(**uintptr)(__ccgo_up(ap + uintptr(i)*4)) = pEntry
			}
			goto _2
		_2:
			;
			pIter = (*TFts5HashEntry)(unsafe.Pointer(pIter)).FpHashNext
		}
		goto _1
	_1:
		;
		iSlot = iSlot + 1
	}
	pList = uintptr(0)
	i = 0
	for {
		if !(i < nMergeSlot) {
			break
		}
		pList = _fts5HashEntryMerge(tls, pList, **(**uintptr)(__ccgo_up(ap + uintptr(i)*4)))
		goto _4
	_4:
		;
		i = i + 1
	}
	Xsqlite3_free(tls, ap)
	**(**uintptr)(__ccgo_up(ppSorted)) = pList
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Resize the hash table by doubling the number of slots.
//	*/
func _fts5HashResize(tls *libc.TLS, pHash uintptr) (r int32) {
	var apNew, apOld, p uintptr
	var i, nNew int32
	var iHash uint32
	_, _, _, _, _, _ = apNew, apOld, i, iHash, nNew, p
	nNew = (*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot * int32(2)
	apOld = (*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot
	apNew = Xsqlite3_malloc64(tls, uint64(libc.Uint32FromInt32(nNew)*uint32(4)))
	if !(apNew != 0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, apNew, 0, libc.Uint32FromInt32(nNew)*uint32(4))
	i = 0
	for {
		if !(i < (*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot) {
			break
		}
		for **(**uintptr)(__ccgo_up(apOld + uintptr(i)*4)) != 0 {
			p = **(**uintptr)(__ccgo_up(apOld + uintptr(i)*4))
			**(**uintptr)(__ccgo_up(apOld + uintptr(i)*4)) = (*TFts5HashEntry)(unsafe.Pointer(p)).FpHashNext
			iHash = _fts5HashKey(tls, nNew, p+1*40, (*TFts5HashEntry)(unsafe.Pointer(p)).FnKey)
			(*TFts5HashEntry)(unsafe.Pointer(p)).FpHashNext = **(**uintptr)(__ccgo_up(apNew + uintptr(iHash)*4))
			**(**uintptr)(__ccgo_up(apNew + uintptr(iHash)*4)) = p
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	Xsqlite3_free(tls, apOld)
	(*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot = nNew
	(*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot = apNew
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Add a tombstone for rowid iRowid to segment pSeg.
//	*/
func _fts5IndexTombstoneAdd(tls *libc.TLS, p uintptr, pSeg uintptr, iRowid Tu64) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iPg, ii, szKey, v1, v2 int32
	var iTombstoneRowid Ti64
	var pPg uintptr
	var _ /* apHash at bp+4 */ uintptr
	var _ /* nHash at bp+0 */ int32
	_, _, _, _, _, _, _ = iPg, iTombstoneRowid, ii, pPg, szKey, v1, v2
	pPg = uintptr(0)
	iPg = -int32(1)
	szKey = 0
	**(**int32)(__ccgo_up(bp)) = 0
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
	(*TFts5Index)(unsafe.Pointer(p)).FnContentlessDelete = (*TFts5Index)(unsafe.Pointer(p)).FnContentlessDelete + 1
	if (*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FnPgTombstone > 0 {
		iPg = libc.Int32FromUint64(iRowid % libc.Uint64FromInt32((*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FnPgTombstone))
		pPg = _fts5DataRead(tls, p, int64((*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FiSegid+libc.Int32FromInt32(1)<<libc.Int32FromInt32(16))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B)+libc.Int32FromInt32(FTS5_DATA_DLI_B))+int64(libc.Int32FromInt32(0))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B))+int64(libc.Int32FromInt32(0))<<libc.Int32FromInt32(FTS5_DATA_PAGE_B)+int64(iPg))
		if pPg == uintptr(0) {
			return
		}
		if 0 == _fts5IndexTombstoneAddToPage(tls, pPg, 0, (*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FnPgTombstone, iRowid) {
			_fts5DataWrite(tls, p, int64((*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FiSegid+libc.Int32FromInt32(1)<<libc.Int32FromInt32(16))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B)+libc.Int32FromInt32(FTS5_DATA_DLI_B))+int64(libc.Int32FromInt32(0))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B))+int64(libc.Int32FromInt32(0))<<libc.Int32FromInt32(FTS5_DATA_PAGE_B)+int64(iPg), (*TFts5Data)(unsafe.Pointer(pPg)).Fp, (*TFts5Data)(unsafe.Pointer(pPg)).Fnn)
			_fts5DataRelease(tls, pPg)
			return
		}
	}
	/* Have to rebuild the hash table. First figure out the key-size (4 or 8). */
	if pPg != 0 {
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Data)(unsafe.Pointer(pPg)).Fp))) == int32(4) {
			v2 = int32(4)
		} else {
			v2 = int32(8)
		}
		v1 = v2
	} else {
		v1 = int32(4)
	}
	szKey = v1
	if iRowid > uint64(0xFFFFFFFF) {
		szKey = int32(8)
	}
	/* Rebuild the hash table */
	_fts5IndexTombstoneRebuild(tls, p, pSeg, pPg, iPg, szKey, bp, bp+4)
	/* If all has succeeded, write the new rowid into one of the new hash
	 ** table pages, then write them all out to disk. */
	if **(**int32)(__ccgo_up(bp)) != 0 {
		ii = 0
		_fts5IndexTombstoneAddToPage(tls, **(**uintptr)(__ccgo_up(**(**uintptr)(__ccgo_up(bp + 4)) + uintptr(iRowid%libc.Uint64FromInt32(**(**int32)(__ccgo_up(bp))))*4)), int32(1), **(**int32)(__ccgo_up(bp)), iRowid)
		ii = 0
		for {
			if !(ii < **(**int32)(__ccgo_up(bp))) {
				break
			}
			iTombstoneRowid = int64((*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FiSegid+libc.Int32FromInt32(1)<<libc.Int32FromInt32(16))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B)+libc.Int32FromInt32(FTS5_DATA_DLI_B)) + int64(libc.Int32FromInt32(0))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B)) + int64(libc.Int32FromInt32(0))<<libc.Int32FromInt32(FTS5_DATA_PAGE_B) + int64(ii)
			_fts5DataWrite(tls, p, iTombstoneRowid, (*TFts5Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(**(**uintptr)(__ccgo_up(bp + 4)) + uintptr(ii)*4)))).Fp, (*TFts5Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(**(**uintptr)(__ccgo_up(bp + 4)) + uintptr(ii)*4)))).Fnn)
			goto _3
		_3:
			;
			ii = ii + 1
		}
		(*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FnPgTombstone = **(**int32)(__ccgo_up(bp))
		_fts5StructureWrite(tls, p, (*TFts5Index)(unsafe.Pointer(p)).FpStruct)
	}
	_fts5DataRelease(tls, pPg)
	_fts5IndexFreeArray(tls, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp)))
}

// C documentation
//
//	/*
//	** This function attempts to build a new hash containing all the keys
//	** currently in the tombstone hash table for segment pSeg. The new
//	** hash will be stored in the nOut buffers passed in array apOut[].
//	** All pages of the new hash use key-size szKey (4 or 8).
//	**
//	** Return 0 if the hash is successfully rebuilt into the nOut pages.
//	** Or non-zero if it is not (because one page became overfull). In this
//	** case the caller should retry with a larger nOut parameter.
//	**
//	** Parameter pData1 is page iPg1 of the hash table being rebuilt.
//	*/
func _fts5IndexTombstoneRehash(tls *libc.TLS, p uintptr, pSeg uintptr, pData1 uintptr, iPg1 int32, szKey int32, nOut int32, apOut uintptr) (r int32) {
	var aSlot, aSlot1, pData, pFree, pPg, v3 uintptr
	var iIn, ii, nSlotIn, res, szKeyIn, v4 int32
	var iVal Tu64
	_, _, _, _, _, _, _, _, _, _, _, _, _ = aSlot, aSlot1, iIn, iVal, ii, nSlotIn, pData, pFree, pPg, res, szKeyIn, v3, v4
	res = 0
	/* Initialize the headers of all the output pages */
	ii = 0
	for {
		if !(ii < nOut) {
			break
		}
		**(**Tu8)(__ccgo_up((*TFts5Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apOut + uintptr(ii)*4)))).Fp)) = libc.Uint8FromInt32(szKey)
		_fts5PutU32(tls, (*TFts5Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apOut + uintptr(ii)*4)))).Fp+4, uint32(0))
		goto _1
	_1:
		;
		ii = ii + 1
	}
	/* Loop through the current pages of the hash table. */
	ii = 0
	for {
		if !(res == 0 && ii < (*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FnPgTombstone) {
			break
		}
		pData = uintptr(0) /* Page ii of the current hash table */
		pFree = uintptr(0) /* Free this at the end of the loop */
		if iPg1 == ii {
			pData = pData1
		} else {
			v3 = _fts5DataRead(tls, p, int64((*TFts5StructureSegment)(unsafe.Pointer(pSeg)).FiSegid+libc.Int32FromInt32(1)<<libc.Int32FromInt32(16))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B)+libc.Int32FromInt32(FTS5_DATA_DLI_B))+int64(libc.Int32FromInt32(0))<<(libc.Int32FromInt32(FTS5_DATA_PAGE_B)+libc.Int32FromInt32(FTS5_DATA_HEIGHT_B))+int64(libc.Int32FromInt32(0))<<libc.Int32FromInt32(FTS5_DATA_PAGE_B)+int64(ii))
			pData = v3
			pFree = v3
		}
		if pData != 0 {
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Data)(unsafe.Pointer(pData)).Fp))) == int32(4) {
				v4 = int32(4)
			} else {
				v4 = int32(8)
			}
			szKeyIn = v4
			nSlotIn = ((*TFts5Data)(unsafe.Pointer(pData)).Fnn - int32(8)) / szKeyIn
			iIn = 0
			for {
				if !(iIn < nSlotIn) {
					break
				}
				iVal = uint64(0)
				/* Read the value from slot iIn of the input page into iVal. */
				if szKeyIn == int32(4) {
					aSlot = (*TFts5Data)(unsafe.Pointer(pData)).Fp + 8
					if **(**Tu32)(__ccgo_up(aSlot + uintptr(iIn)*4)) != 0 {
						iVal = uint64(_fts5GetU32(tls, aSlot+uintptr(iIn)*4))
					}
				} else {
					aSlot1 = (*TFts5Data)(unsafe.Pointer(pData)).Fp + 8
					if **(**Tu64)(__ccgo_up(aSlot1 + uintptr(iIn)*8)) != 0 {
						iVal = _fts5GetU64(tls, aSlot1+uintptr(iIn)*8)
					}
				}
				/* If iVal is not 0 at this point, insert it into the new hash table */
				if iVal != 0 {
					pPg = **(**uintptr)(__ccgo_up(apOut + uintptr(iVal%libc.Uint64FromInt32(nOut))*4))
					res = _fts5IndexTombstoneAddToPage(tls, pPg, 0, nOut, iVal)
					if res != 0 {
						break
					}
				}
				goto _5
			_5:
				;
				iIn = iIn + 1
			}
			/* If this is page 0 of the old hash, copy the rowid-0-flag from the
			 ** old hash to the new.  */
			if ii == 0 {
				**(**Tu8)(__ccgo_up((*TFts5Data)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apOut)))).Fp + 1)) = **(**Tu8)(__ccgo_up((*TFts5Data)(unsafe.Pointer(pData)).Fp + 1))
			}
		}
		_fts5DataRelease(tls, pFree)
		goto _2
	_2:
		;
		ii = ii + 1
	}
	return res
}

// C documentation
//
//	/*
//	** pToken points to a buffer of size nToken bytes containing a search
//	** term, including the index number at the start, used on a tokendata=1
//	** table. This function returns true if the term in buffer pBuf matches
//	** token pToken/nToken.
//	*/
func _fts5IsTokendataPrefix(tls *libc.TLS, pBuf uintptr, pToken uintptr, nToken int32) (r int32) {
	return libc.BoolInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn >= nToken && 0 == libc.Xmemcmp(tls, (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp, pToken, libc.Uint32FromInt32(nToken)) && ((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn == nToken || libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp + uintptr(nToken)))) == 0x00))
}

// C documentation
//
//	/*
//	** xSetOutputs callback used when:
//	**
//	**   * detail=col,
//	**   * there is a column filter, and
//	**   * the table contains 100 or fewer columns.
//	**
//	** The last point is to ensure all column numbers are stored as
//	** single-byte varints.
//	*/
func _fts5IterSetOutputs_Col100(tls *libc.TLS, pIter uintptr, pSeg uintptr) {
	var a, aOut, aiCol, aiColEnd, pEnd, v1 uintptr
	var iPrev, iPrevOut int32
	_, _, _, _, _, _, _, _ = a, aOut, aiCol, aiColEnd, iPrev, iPrevOut, pEnd, v1
	if (*TFts5SegIter)(unsafe.Pointer(pSeg)).FiLeafOffset+int64((*TFts5SegIter)(unsafe.Pointer(pSeg)).FnPos) > int64((*TFts5Data)(unsafe.Pointer((*TFts5SegIter)(unsafe.Pointer(pSeg)).FpLeaf)).FszLeaf) || (*TFts5SegIter)(unsafe.Pointer(pSeg)).FnPos > (*TFts5Config)(unsafe.Pointer((*TFts5Index)(unsafe.Pointer((*TFts5Iter)(unsafe.Pointer(pIter)).FpIndex)).FpConfig)).FnCol {
		_fts5IterSetOutputs_Col(tls, pIter, pSeg)
	} else {
		a = (*TFts5Data)(unsafe.Pointer((*TFts5SegIter)(unsafe.Pointer(pSeg)).FpLeaf)).Fp + uintptr((*TFts5SegIter)(unsafe.Pointer(pSeg)).FiLeafOffset)
		pEnd = a + uintptr((*TFts5SegIter)(unsafe.Pointer(pSeg)).FnPos)
		iPrev = 0
		aiCol = (*TFts5Iter)(unsafe.Pointer(pIter)).FpColset + 4
		aiColEnd = aiCol + uintptr((*TFts5Colset)(unsafe.Pointer((*TFts5Iter)(unsafe.Pointer(pIter)).FpColset)).FnCol)*4
		aOut = (*TFts5Iter)(unsafe.Pointer(pIter)).Fposlist.Fp
		iPrevOut = 0
		(*TFts5Iter)(unsafe.Pointer(pIter)).Fbase.FiRowid = (*TFts5SegIter)(unsafe.Pointer(pSeg)).FiRowid
		for a < pEnd {
			v1 = a
			a = a + 1
			iPrev = iPrev + (libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v1))) - int32(2))
			for **(**int32)(__ccgo_up(aiCol)) < iPrev {
				aiCol += 4
				if aiCol == aiColEnd {
					goto setoutputs_col_out
				}
			}
			if **(**int32)(__ccgo_up(aiCol)) == iPrev {
				v1 = aOut
				aOut = aOut + 1
				**(**Tu8)(__ccgo_up(v1)) = libc.Uint8FromInt32(iPrev - iPrevOut + libc.Int32FromInt32(2))
				iPrevOut = iPrev
			}
		}
		goto setoutputs_col_out
	setoutputs_col_out:
		;
		(*TFts5Iter)(unsafe.Pointer(pIter)).Fbase.FpData = (*TFts5Iter)(unsafe.Pointer(pIter)).Fposlist.Fp
		(*TFts5Iter)(unsafe.Pointer(pIter)).Fbase.FnData = int32(aOut) - int32((*TFts5Iter)(unsafe.Pointer(pIter)).Fposlist.Fp)
	}
}

// C documentation
//
//	/*
//	** This function is used by xCreateTokenizer_v2() and xCreateTokenizer().
//	** It allocates and partially populates a new Fts5TokenizerModule object.
//	** The new object is already linked into the Fts5Global context before
//	** returning.
//	**
//	** If successful, SQLITE_OK is returned and a pointer to the new
//	** Fts5TokenizerModule object returned via output parameter (*ppNew). All
//	** that is required is for the caller to fill in the methods in
//	** Fts5TokenizerModule.x1 and x2, and to set Fts5TokenizerModule.bV2Native
//	** as appropriate.
//	**
//	** If an error occurs, an SQLite error code is returned and the final value
//	** of (*ppNew) undefined.
//	*/
func _fts5NewTokenizerModule(tls *libc.TLS, pGlobal uintptr, zName uintptr, pUserData uintptr, __ccgo_fp_xDestroy uintptr, ppNew uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nByte, nName Tsqlite3_int64
	var pNew, v1 uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _, _ = nByte, nName, pNew, v1
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK /* Bytes of space to allocate */
	nName = libc.Int64FromUint32(libc.Xstrlen(tls, zName) + uint32(1))
	nByte = int64(48) + nName
	v1 = _sqlite3Fts5MallocZero(tls, bp, nByte)
	pNew = v1
	**(**uintptr)(__ccgo_up(ppNew)) = v1
	if pNew != 0 {
		(*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FzName = pNew + 1*48
		libc.Xmemcpy(tls, (*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FzName, zName, libc.Uint32FromInt64(nName))
		(*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FpUserData = pUserData
		(*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FxDestroy = __ccgo_fp_xDestroy
		(*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FpNext = (*TFts5Global)(unsafe.Pointer(pGlobal)).FpTok
		(*TFts5Global)(unsafe.Pointer(pGlobal)).FpTok = pNew
		if (*TFts5TokenizerModule)(unsafe.Pointer(pNew)).FpNext == uintptr(0) {
			(*TFts5Global)(unsafe.Pointer(pGlobal)).FpDfltTok = pNew
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** The second argument passed to this function may be NULL, or it may be
//	** an existing Fts5Colset object. This function returns a pointer to
//	** a new colset object containing the contents of (p) with new value column
//	** number iCol appended.
//	**
//	** If an OOM error occurs, store an error code in pParse and return NULL.
//	** The old colset object (if any) is not freed in this case.
//	*/
func _fts5ParseColset(tls *libc.TLS, pParse uintptr, p uintptr, iCol int32) (r uintptr) {
	var aiCol, pNew uintptr
	var i, j, nCol, v1 int32
	_, _, _, _, _, _ = aiCol, i, j, nCol, pNew, v1
	if p != 0 {
		v1 = (*TFts5Colset)(unsafe.Pointer(p)).FnCol
	} else {
		v1 = 0
	}
	nCol = v1 /* New colset object to return */
	pNew = Xsqlite3_realloc64(tls, p, uint64(libc.Uint32FromInt64(8)*libc.Uint32FromInt32((nCol+libc.Int32FromInt32(1)+libc.Int32FromInt32(2))/libc.Int32FromInt32(2))))
	if pNew == uintptr(0) {
		(*TFts5Parse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
	} else {
		aiCol = pNew + 4
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			if **(**int32)(__ccgo_up(aiCol + uintptr(i)*4)) == iCol {
				return pNew
			}
			if **(**int32)(__ccgo_up(aiCol + uintptr(i)*4)) > iCol {
				break
			}
			goto _2
		_2:
			;
			i = i + 1
		}
		j = nCol
		for {
			if !(j > i) {
				break
			}
			**(**int32)(__ccgo_up(aiCol + uintptr(j)*4)) = **(**int32)(__ccgo_up(aiCol + uintptr(j-int32(1))*4))
			goto _3
		_3:
			;
			j = j - 1
		}
		**(**int32)(__ccgo_up(aiCol + uintptr(i)*4)) = iCol
		(*TFts5Colset)(unsafe.Pointer(pNew)).FnCol = nCol + int32(1)
	}
	return pNew
}

// C documentation
//
//	/*
//	** Callback for tokenizing terms used by ParseTerm().
//	*/
func _fts5ParseTokenize(tls *libc.TLS, pContext uintptr, tflags int32, pToken uintptr, nToken int32, iUnused1 int32, iUnused2 int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var SZALLOC, nNew, v1 int32
	var nByte Tsqlite3_int64
	var pCtx, pNew, pPhrase, pSyn, pTerm, v3 uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _ = SZALLOC, nByte, nNew, pCtx, pNew, pPhrase, pSyn, pTerm, v1, v3
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	SZALLOC = int32(8)
	pCtx = pContext
	pPhrase = (*TTokenCtx)(unsafe.Pointer(pCtx)).FpPhrase
	_ = iUnused1
	_ = iUnused2
	/* If an error has already occurred, this is a no-op */
	if (*TTokenCtx)(unsafe.Pointer(pCtx)).Frc != SQLITE_OK {
		return (*TTokenCtx)(unsafe.Pointer(pCtx)).Frc
	}
	if nToken > int32(FTS5_MAX_TOKEN_SIZE) {
		nToken = int32(FTS5_MAX_TOKEN_SIZE)
	}
	if pPhrase != 0 && (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm > 0 && tflags&int32(FTS5_TOKEN_COLOCATED) != 0 {
		nByte = libc.Int64FromUint32(libc.Uint32FromInt64(24) + libc.Uint32FromInt64(12) + libc.Uint32FromInt32(nToken) + uint32(1))
		pSyn = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if pSyn == uintptr(0) {
			**(**int32)(__ccgo_up(bp)) = int32(SQLITE_NOMEM)
		} else {
			libc.Xmemset(tls, pSyn, 0, libc.Uint32FromInt64(nByte))
			(*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FpTerm = pSyn + uintptr(24) + uintptr(12)
			v1 = nToken
			(*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FnQueryTerm = v1
			(*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FnFullTerm = v1
			libc.Xmemcpy(tls, (*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FpTerm, pToken, libc.Uint32FromInt32(nToken))
			if (*TFts5Config)(unsafe.Pointer((*TTokenCtx)(unsafe.Pointer(pCtx)).FpConfig)).FbTokendata != 0 {
				(*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FnQueryTerm = libc.Int32FromUint32(libc.Xstrlen(tls, (*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FpTerm))
			}
			(*TFts5ExprTerm)(unsafe.Pointer(pSyn)).FpSynonym = (*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase + 20 + uintptr((*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm-int32(1))*24))).FpSynonym
			(*(*TFts5ExprTerm)(unsafe.Pointer(pPhrase + 20 + uintptr((*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm-int32(1))*24))).FpSynonym = pSyn
		}
	} else {
		if pPhrase == uintptr(0) || (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm%SZALLOC == 0 {
			if pPhrase != 0 {
				v1 = (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm
			} else {
				v1 = 0
			}
			nNew = SZALLOC + v1
			pNew = Xsqlite3_realloc64(tls, pPhrase, uint64(uint32(libc.UintptrFromInt32(0)+20)+libc.Uint32FromInt32(nNew+libc.Int32FromInt32(1))*libc.Uint32FromInt64(24)))
			if pNew == uintptr(0) {
				**(**int32)(__ccgo_up(bp)) = int32(SQLITE_NOMEM)
			} else {
				if pPhrase == uintptr(0) {
					libc.Xmemset(tls, pNew, 0, uint32(libc.UintptrFromInt32(0)+20)+libc.Uint32FromInt32(libc.Int32FromInt32(1))*libc.Uint32FromInt64(24))
				}
				v3 = pNew
				pPhrase = v3
				(*TTokenCtx)(unsafe.Pointer(pCtx)).FpPhrase = v3
				(*TFts5ExprPhrase)(unsafe.Pointer(pNew)).FnTerm = nNew - SZALLOC
			}
		}
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			v3 = pPhrase + 16
			v1 = *(*int32)(unsafe.Pointer(v3))
			*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
			pTerm = pPhrase + 20 + uintptr(v1)*24
			libc.Xmemset(tls, pTerm, 0, uint32(24))
			(*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpTerm = _sqlite3Fts5Strndup(tls, bp, pToken, nToken)
			v1 = nToken
			(*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FnQueryTerm = v1
			(*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FnFullTerm = v1
			if (*TFts5Config)(unsafe.Pointer((*TTokenCtx)(unsafe.Pointer(pCtx)).FpConfig)).FbTokendata != 0 && **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
				(*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FnQueryTerm = libc.Int32FromUint32(libc.Xstrlen(tls, (*TFts5ExprTerm)(unsafe.Pointer(pTerm)).FpTerm))
			}
		}
	}
	(*TTokenCtx)(unsafe.Pointer(pCtx)).Frc = **(**int32)(__ccgo_up(bp))
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Return a "position-list blob" corresponding to the current position of
//	** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
//	** the current position-list for each phrase in the query associated with
//	** cursor pCsr.
//	**
//	** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
//	** the number of phrases in the query. Following the varints are the
//	** concatenated position lists for each phrase, in order.
//	**
//	** The first varint (if it exists) contains the size of the position list
//	** for phrase 0. The second (same disclaimer) contains the size of position
//	** list 1. And so on. There is no size field for the final position list,
//	** as it can be derived from the total size of the blob.
//	*/
func _fts5PoslistBlob(tls *libc.TLS, pCtx uintptr, pCsr uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var i, nByte, nPhrase, nPoslist int32
	var _ /* dummy at bp+16 */ uintptr
	var _ /* dummy at bp+24 */ uintptr
	var _ /* nByte at bp+28 */ int32
	var _ /* nPoslist at bp+36 */ int32
	var _ /* pPoslist at bp+20 */ uintptr
	var _ /* pPoslist at bp+32 */ uintptr
	var _ /* rc at bp+0 */ int32
	var _ /* val at bp+4 */ TFts5Buffer
	_, _, _, _ = i, nByte, nPhrase, nPoslist
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	nPhrase = _sqlite3Fts5ExprPhraseCount(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpExpr)
	libc.Xmemset(tls, bp+4, 0, uint32(12))
	switch (*TFts5Config)(unsafe.Pointer((*TFts5Table)(unsafe.Pointer((*TFts5Cursor)(unsafe.Pointer(pCsr)).Fbase.FpVtab)).FpConfig)).FeDetail {
	case FTS5_DETAIL_FULL:
		goto _1
	case int32(FTS5_DETAIL_COLUMNS):
		goto _2
	default:
		goto _3
	}
	goto _4
_1:
	;
	/* Append the varints */
	i = 0
_7:
	;
	if !(i < nPhrase-int32(1)) {
		goto _5
	}
	nByte = _sqlite3Fts5ExprPoslist(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpExpr, i, bp+16)
	_sqlite3Fts5BufferAppendVarint(tls, bp, bp+4, int64(nByte))
	goto _6
_6:
	;
	i = i + 1
	goto _7
	goto _5
_5:
	;
	/* Append the position lists */
	i = 0
	for {
		if !(i < nPhrase) {
			break
		}
		nPoslist = _sqlite3Fts5ExprPoslist(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpExpr, i, bp+20)
		_sqlite3Fts5BufferAppendBlob(tls, bp, bp+4, libc.Uint32FromInt32(nPoslist), **(**uintptr)(__ccgo_up(bp + 20)))
		goto _8
	_8:
		;
		i = i + 1
	}
	goto _4
_2:
	;
	/* Append the varints */
	i = 0
	for {
		if !(**(**int32)(__ccgo_up(bp)) == SQLITE_OK && i < nPhrase-int32(1)) {
			break
		}
		**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5ExprPhraseCollist(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpExpr, i, bp+24, bp+28)
		_sqlite3Fts5BufferAppendVarint(tls, bp, bp+4, int64(**(**int32)(__ccgo_up(bp + 28))))
		goto _9
	_9:
		;
		i = i + 1
	}
	/* Append the position lists */
	i = 0
	for {
		if !(**(**int32)(__ccgo_up(bp)) == SQLITE_OK && i < nPhrase) {
			break
		}
		**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5ExprPhraseCollist(tls, (*TFts5Cursor)(unsafe.Pointer(pCsr)).FpExpr, i, bp+32, bp+36)
		_sqlite3Fts5BufferAppendBlob(tls, bp, bp+4, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 36))), **(**uintptr)(__ccgo_up(bp + 32)))
		goto _10
	_10:
		;
		i = i + 1
	}
	goto _4
_3:
	;
	goto _4
_4:
	;
	Xsqlite3_result_blob(tls, pCtx, (**(**TFts5Buffer)(__ccgo_up(bp + 4))).Fp, (**(**TFts5Buffer)(__ccgo_up(bp + 4))).Fn, __ccgo_fp(Xsqlite3_free))
	return **(**int32)(__ccgo_up(bp))
}

func _fts5PoslistCallback(tls *libc.TLS, pUnused uintptr, pContext uintptr, pChunk uintptr, nChunk int32) {
	_ = pUnused
	if nChunk > 0 {
		libc.Xmemcpy(tls, (*TFts5Buffer)(unsafe.Pointer(pContext)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer(pContext)).Fn), pChunk, libc.Uint32FromInt32(nChunk))
		**(**int32)(__ccgo_up(pContext + 4)) += nChunk
	}
}

func _fts5PoslistFilterCallback(tls *libc.TLS, pUnused uintptr, pContext uintptr, pChunk uintptr, nChunk int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, iEnd, iStart, v1 int32
	var pCtx uintptr
	var _ /* iCol at bp+0 */ int32
	var _ /* iCol at bp+4 */ int32
	_, _, _, _, _ = i, iEnd, iStart, pCtx, v1
	pCtx = pContext
	_ = pUnused
	if nChunk > 0 {
		/* Search through to find the first varint with value 1. This is the
		 ** start of the next columns hits. */
		i = 0
		iStart = 0
		if (*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState == int32(2) {
			v1 = i
			i = i + 1
			**(**int32)(__ccgo_up(bp)) = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pChunk + uintptr(v1))))
			if **(**int32)(__ccgo_up(bp))&int32(0x80) != 0 {
				i = i - 1
				i = i + _sqlite3Fts5GetVarint32(tls, pChunk+uintptr(i), bp)
			}
			if _fts5IndexColsetTest(tls, (*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpColset, **(**int32)(__ccgo_up(bp))) != 0 {
				(*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState = int32(1)
				**(**int32)(__ccgo_up((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf + 4)) += _sqlite3Fts5PutVarint(tls, (*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fn), libc.Uint64FromInt32(libc.Int32FromInt32(1)))
			} else {
				(*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState = 0
			}
		}
		for cond := true; cond; cond = i < nChunk {
			for i < nChunk && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pChunk + uintptr(i)))) != int32(0x01) {
				iEnd = i + int32(9)
				for {
					v1 = i
					i = i + 1
					if !(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pChunk + uintptr(v1))))&int32(0x80) != 0 && i < iEnd) {
						break
					}
				}
			}
			if (*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState != 0 {
				libc.Xmemcpy(tls, (*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fn), pChunk+uintptr(iStart), libc.Uint32FromInt32(i-iStart))
				**(**int32)(__ccgo_up((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf + 4)) += i - iStart
			}
			if i < nChunk {
				iStart = i
				i = i + 1
				if i >= nChunk {
					(*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState = int32(2)
				} else {
					v1 = i
					i = i + 1
					**(**int32)(__ccgo_up(bp + 4)) = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pChunk + uintptr(v1))))
					if **(**int32)(__ccgo_up(bp + 4))&int32(0x80) != 0 {
						i = i - 1
						i = i + _sqlite3Fts5GetVarint32(tls, pChunk+uintptr(i), bp+4)
					}
					(*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState = _fts5IndexColsetTest(tls, (*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpColset, **(**int32)(__ccgo_up(bp + 4)))
					if (*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FeState != 0 {
						libc.Xmemcpy(tls, (*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fn), pChunk+uintptr(iStart), libc.Uint32FromInt32(i-iStart))
						**(**int32)(__ccgo_up((*TPoslistCallbackCtx)(unsafe.Pointer(pCtx)).FpBuf + 4)) += i - iStart
						iStart = i
					}
				}
			}
		}
	}
}

func _fts5PoslistOffsetsCallback(tls *libc.TLS, pUnused uintptr, pContext uintptr, pChunk uintptr, nChunk int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i int32
	var pCtx uintptr
	var _ /* iVal at bp+0 */ int32
	_, _ = i, pCtx
	pCtx = pContext
	_ = pUnused
	if nChunk > 0 {
		i = 0
		for i < nChunk {
			i = i + _sqlite3Fts5GetVarint32(tls, pChunk+uintptr(i), bp)
			**(**int32)(__ccgo_up(bp)) = **(**int32)(__ccgo_up(bp)) + ((*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FiRead - int32(2))
			(*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FiRead = **(**int32)(__ccgo_up(bp))
			if _fts5IndexColsetTest(tls, (*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FpColset, **(**int32)(__ccgo_up(bp))) != 0 {
				**(**int32)(__ccgo_up((*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FpBuf + 4)) += _sqlite3Fts5PutVarint(tls, (*TFts5Buffer)(unsafe.Pointer((*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer((*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FpBuf)).Fn), libc.Uint64FromInt32(**(**int32)(__ccgo_up(bp))+libc.Int32FromInt32(2)-(*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FiWrite))
				(*TPoslistOffsetsCtx)(unsafe.Pointer(pCtx)).FiWrite = **(**int32)(__ccgo_up(bp))
			}
		}
	}
}

// C documentation
//
//	/*
//	** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
//	** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
//	** error occurs.
//	*/
func _fts5SentenceFinderAdd(tls *libc.TLS, p uintptr, iAdd int32) (r int32) {
	var aNew, v3 uintptr
	var nNew, v1 int32
	_, _, _, _ = aNew, nNew, v1, v3
	if (*TFts5SFinder)(unsafe.Pointer(p)).FnFirstAlloc == (*TFts5SFinder)(unsafe.Pointer(p)).FnFirst {
		if (*TFts5SFinder)(unsafe.Pointer(p)).FnFirstAlloc != 0 {
			v1 = (*TFts5SFinder)(unsafe.Pointer(p)).FnFirstAlloc * int32(2)
		} else {
			v1 = int32(64)
		}
		nNew = v1
		aNew = Xsqlite3_realloc64(tls, (*TFts5SFinder)(unsafe.Pointer(p)).FaFirst, uint64(libc.Uint32FromInt32(nNew)*uint32(4)))
		if aNew == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		(*TFts5SFinder)(unsafe.Pointer(p)).FaFirst = aNew
		(*TFts5SFinder)(unsafe.Pointer(p)).FnFirstAlloc = nNew
	}
	v3 = p + 8
	v1 = *(*int32)(unsafe.Pointer(v3))
	*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
	**(**int32)(__ccgo_up((*TFts5SFinder)(unsafe.Pointer(p)).FaFirst + uintptr(v1)*4)) = iAdd
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** If a row with rowid iDel is present in the %_content table, add the
//	** delete-markers to the FTS index necessary to delete it. Do not actually
//	** remove the %_content row at this time though.
//	**
//	** If parameter bSaveRow is true, then Fts5Storage.pSavedRow is left
//	** pointing to a statement (FTS5_STMT_LOOKUP2) that may be used to access
//	** the original values of the row being deleted. This is used by UPDATE
//	** statements.
//	*/
func _fts5StorageDeleteFromIndex(tls *libc.TLS, p uintptr, iDel Ti64, apVal uintptr, bSaveRow int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var iCol, rc, rc2 int32
	var pConfig, pFree, pVal, v2 uintptr
	var _ /* ctx at bp+4 */ TFts5InsertCtx
	var _ /* nLoc at bp+28 */ int32
	var _ /* nText at bp+20 */ int32
	var _ /* pLoc at bp+24 */ uintptr
	var _ /* pSeek at bp+0 */ uintptr
	var _ /* pText at bp+16 */ uintptr
	_, _, _, _, _, _, _ = iCol, pConfig, pFree, pVal, rc, rc2, v2
	pConfig = (*TFts5Storage)(unsafe.Pointer(p)).FpConfig
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0) /* SELECT to read row iDel from %_data */
	rc = SQLITE_OK
	if apVal == uintptr(0) {
		if (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow != 0 && bSaveRow != 0 {
			**(**uintptr)(__ccgo_up(bp)) = (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow
			(*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow = uintptr(0)
		} else {
			rc = _fts5StorageGetStmt(tls, p, int32(FTS5_STMT_LOOKUP)+bSaveRow, bp, uintptr(0))
			if rc != SQLITE_OK {
				return rc
			}
			Xsqlite3_bind_int64(tls, **(**uintptr)(__ccgo_up(bp)), int32(1), iDel)
			if Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp))) != int32(SQLITE_ROW) {
				return Xsqlite3_reset(tls, **(**uintptr)(__ccgo_up(bp)))
			}
		}
	}
	(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FpStorage = p
	(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol = -int32(1)
	iCol = int32(1)
	for {
		if !(rc == SQLITE_OK && iCol <= (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol) {
			break
		}
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Config)(unsafe.Pointer(pConfig)).FabUnindexed + uintptr(iCol-int32(1))))) == 0 {
			pVal = uintptr(0)
			pFree = uintptr(0)
			**(**uintptr)(__ccgo_up(bp + 16)) = uintptr(0)
			**(**int32)(__ccgo_up(bp + 20)) = 0
			**(**uintptr)(__ccgo_up(bp + 24)) = uintptr(0)
			**(**int32)(__ccgo_up(bp + 28)) = 0
			if **(**uintptr)(__ccgo_up(bp)) != 0 {
				pVal = Xsqlite3_column_value(tls, **(**uintptr)(__ccgo_up(bp)), iCol)
			} else {
				pVal = **(**uintptr)(__ccgo_up(apVal + uintptr(iCol-int32(1))*4))
			}
			if (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 && _sqlite3Fts5IsLocaleValue(tls, pConfig, pVal) != 0 {
				rc = _sqlite3Fts5DecodeLocaleValue(tls, pVal, bp+16, bp+20, bp+24, bp+28)
			} else {
				if Xsqlite3_value_type(tls, pVal) != int32(SQLITE_TEXT) {
					/* Make a copy of the value to work with. This is because the call
					 ** to sqlite3_value_text() below forces the type of the value to
					 ** SQLITE_TEXT, and we may need to use it again later. */
					v2 = Xsqlite3_value_dup(tls, pVal)
					pVal = v2
					pFree = v2
					if pVal == uintptr(0) {
						rc = int32(SQLITE_NOMEM)
					}
				}
				if rc == SQLITE_OK {
					**(**uintptr)(__ccgo_up(bp + 16)) = Xsqlite3_value_text(tls, pVal)
					**(**int32)(__ccgo_up(bp + 20)) = Xsqlite3_value_bytes(tls, pVal)
					if (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 && **(**uintptr)(__ccgo_up(bp)) != 0 {
						**(**uintptr)(__ccgo_up(bp + 24)) = Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), iCol+(*TFts5Config)(unsafe.Pointer(pConfig)).FnCol)
						**(**int32)(__ccgo_up(bp + 28)) = Xsqlite3_column_bytes(tls, **(**uintptr)(__ccgo_up(bp)), iCol+(*TFts5Config)(unsafe.Pointer(pConfig)).FnCol)
					}
				}
			}
			if rc == SQLITE_OK {
				_sqlite3Fts5SetLocale(tls, pConfig, **(**uintptr)(__ccgo_up(bp + 24)), **(**int32)(__ccgo_up(bp + 28)))
				(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FszCol = 0
				rc = _sqlite3Fts5Tokenize(tls, pConfig, int32(FTS5_TOKENIZE_DOCUMENT), **(**uintptr)(__ccgo_up(bp + 16)), **(**int32)(__ccgo_up(bp + 20)), bp+4, __ccgo_fp(_fts5StorageInsertCallback))
				**(**Ti64)(__ccgo_up((*TFts5Storage)(unsafe.Pointer(p)).FaTotalSize + uintptr(iCol-int32(1))*8)) -= int64((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FszCol)
				if rc == SQLITE_OK && **(**Ti64)(__ccgo_up((*TFts5Storage)(unsafe.Pointer(p)).FaTotalSize + uintptr(iCol-int32(1))*8)) < 0 {
					rc = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
				}
				_sqlite3Fts5ClearLocale(tls, pConfig)
			}
			Xsqlite3_value_free(tls, pFree)
		}
		goto _1
	_1:
		;
		iCol = iCol + 1
	}
	if rc == SQLITE_OK && (*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow < int64(1) {
		rc = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
	} else {
		(*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow = (*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow - 1
	}
	if rc == SQLITE_OK && bSaveRow != 0 {
		(*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow = **(**uintptr)(__ccgo_up(bp))
	} else {
		rc2 = Xsqlite3_reset(tls, **(**uintptr)(__ccgo_up(bp)))
		if rc == SQLITE_OK {
			rc = rc2
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Append a mapping to the token-map belonging to object pT.
//	*/
func _fts5TokendataIterAppendMap(tls *libc.TLS, p uintptr, pT uintptr, iIter int32, nByte int32, iRowid Ti64, iPos Ti64) {
	var aNew uintptr
	var nAlloc, nNew Ti64
	var v1 int64
	_, _, _, _ = aNew, nAlloc, nNew, v1
	if (*TFts5Index)(unsafe.Pointer(p)).Frc == SQLITE_OK {
		if (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap == (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMapAlloc {
			if (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMapAlloc != 0 {
				v1 = (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMapAlloc * int64(2)
			} else {
				v1 = int64(64)
			}
			nNew = v1
			nAlloc = nNew * int64(24)
			aNew = Xsqlite3_realloc64(tls, (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap, libc.Uint64FromInt64(nAlloc))
			if aNew == uintptr(0) {
				(*TFts5Index)(unsafe.Pointer(p)).Frc = int32(SQLITE_NOMEM)
				return
			}
			(*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap = aNew
			(*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMapAlloc = nNew
		}
		(**(**TFts5TokenDataMap)(__ccgo_up((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap + uintptr((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap)*24))).FiRowid = iRowid
		(**(**TFts5TokenDataMap)(__ccgo_up((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap + uintptr((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap)*24))).FiPos = iPos
		(**(**TFts5TokenDataMap)(__ccgo_up((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap + uintptr((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap)*24))).FiIter = iIter
		(**(**TFts5TokenDataMap)(__ccgo_up((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FaMap + uintptr((*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap)*24))).FnByte = nByte
		(*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap = (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnMap + 1
	}
}

// C documentation
//
//	/*
//	** The iterator passed as the only argument must be a tokendata=1 iterator
//	** (pIter->pTokenDataIter!=0). This function advances the iterator. If
//	** argument bFrom is false, then the iterator is advanced to the next
//	** entry. Or, if bFrom is true, it is advanced to the first entry with
//	** a rowid of iFrom or greater.
//	*/
func _fts5TokendataIterNext(tls *libc.TLS, pIter uintptr, bFrom int32, iFrom Ti64) {
	var ii int32
	var p, pIndex, pT uintptr
	_, _, _, _ = ii, p, pIndex, pT
	pT = (*TFts5Iter)(unsafe.Pointer(pIter)).FpTokenDataIter
	pIndex = (*TFts5Iter)(unsafe.Pointer(pIter)).FpIndex
	ii = 0
	for {
		if !(int64(ii) < (*TFts5TokenDataIter)(unsafe.Pointer(pT)).FnIter) {
			break
		}
		p = *(*uintptr)(unsafe.Pointer(pT + 56 + uintptr(ii)*4))
		if libc.Int32FromUint8((*TFts5Iter)(unsafe.Pointer(p)).Fbase.FbEof) == 0 && ((*TFts5Iter)(unsafe.Pointer(p)).Fbase.FiRowid == (*TFts5Iter)(unsafe.Pointer(pIter)).Fbase.FiRowid || bFrom != 0 && (*TFts5Iter)(unsafe.Pointer(p)).Fbase.FiRowid < iFrom) {
			_fts5MultiIterNext(tls, pIndex, p, bFrom, iFrom)
			for bFrom != 0 && libc.Int32FromUint8((*TFts5Iter)(unsafe.Pointer(p)).Fbase.FbEof) == 0 && (*TFts5Iter)(unsafe.Pointer(p)).Fbase.FiRowid < iFrom && (*TFts5Index)(unsafe.Pointer(pIndex)).Frc == SQLITE_OK {
				_fts5MultiIterNext(tls, pIndex, p, 0, 0)
			}
		}
		goto _1
	_1:
		;
		ii = ii + 1
	}
	if (*TFts5Index)(unsafe.Pointer(pIndex)).Frc == SQLITE_OK {
		_fts5IterSetOutputsTokendata(tls, pIter)
	}
}

func _fts5UnicodeAddExceptions(tls *libc.TLS, p uintptr, z uintptr, bTokenChars int32) (r int32) {
	var aNew, zCsr, zTerm, v1 uintptr
	var bToken, i, n, nNew, rc int32
	var iCode Tu32
	_, _, _, _, _, _, _, _, _, _ = aNew, bToken, i, iCode, n, nNew, rc, zCsr, zTerm, v1
	rc = SQLITE_OK
	n = libc.Int32FromUint32(libc.Xstrlen(tls, z))
	if n > 0 {
		aNew = Xsqlite3_realloc64(tls, (*TUnicode61Tokenizer)(unsafe.Pointer(p)).FaiException, uint64(libc.Uint32FromInt32(n+(*TUnicode61Tokenizer)(unsafe.Pointer(p)).FnException)*uint32(4)))
		if aNew != 0 {
			nNew = (*TUnicode61Tokenizer)(unsafe.Pointer(p)).FnException
			zCsr = z
			zTerm = z + uintptr(n)
			for zCsr < zTerm {
				v1 = zCsr
				zCsr = zCsr + 1
				iCode = uint32(**(**uint8)(__ccgo_up(v1)))
				if iCode >= uint32(0xc0) {
					iCode = uint32(_sqlite3Utf8Trans1[iCode-uint32(0xc0)])
					for zCsr < zTerm && libc.Int32FromUint8(**(**uint8)(__ccgo_up(zCsr)))&int32(0xc0) == int32(0x80) {
						v1 = zCsr
						zCsr = zCsr + 1
						iCode = iCode<<libc.Int32FromInt32(6) + libc.Uint32FromInt32(libc.Int32FromInt32(0x3f)&libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))))
					}
					if iCode < uint32(0x80) || iCode&uint32(0xFFFFF800) == uint32(0xD800) || iCode&uint32(0xFFFFFFFE) == uint32(0xFFFE) {
						iCode = uint32(0xFFFD)
					}
				}
				if iCode < uint32(128) {
					**(**uint8)(__ccgo_up(p + uintptr(iCode))) = libc.Uint8FromInt32(bTokenChars)
				} else {
					bToken = libc.Int32FromUint8(**(**uint8)(__ccgo_up(p + 148 + uintptr(_sqlite3Fts5UnicodeCategory(tls, iCode)))))
					if bToken != bTokenChars && _sqlite3Fts5UnicodeIsdiacritic(tls, libc.Int32FromUint32(iCode)) == 0 {
						i = 0
						for {
							if !(i < nNew) {
								break
							}
							if libc.Uint32FromInt32(**(**int32)(__ccgo_up(aNew + uintptr(i)*4))) > iCode {
								break
							}
							goto _3
						_3:
							;
							i = i + 1
						}
						libc.Xmemmove(tls, aNew+uintptr(i+int32(1))*4, aNew+uintptr(i)*4, libc.Uint32FromInt32(nNew-i)*uint32(4))
						**(**int32)(__ccgo_up(aNew + uintptr(i)*4)) = libc.Int32FromUint32(iCode)
						nNew = nNew + 1
					}
				}
			}
			(*TUnicode61Tokenizer)(unsafe.Pointer(p)).FaiException = aNew
			(*TUnicode61Tokenizer)(unsafe.Pointer(p)).FnException = nNew
		} else {
			rc = int32(SQLITE_NOMEM)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Return true if, for the purposes of tokenizing with the tokenizer
//	** passed as the first argument, codepoint iCode is considered a token
//	** character (not a separator).
//	*/
func _fts5UnicodeIsAlnum(tls *libc.TLS, p uintptr, iCode int32) (r int32) {
	return libc.Int32FromUint8(**(**uint8)(__ccgo_up(p + 148 + uintptr(_sqlite3Fts5UnicodeCategory(tls, libc.Uint32FromInt32(iCode)))))) ^ _fts5UnicodeIsException(tls, p, iCode)
}

func _fts5VocabInstanceNewTerm(tls *libc.TLS, pCsr uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var bCmp, nCmp, v1 int32
	var zTerm uintptr
	var _ /* nTerm at bp+4 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _ = bCmp, nCmp, zTerm, v1
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	if (*TFts5IndexIter)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)).FbEof != 0 {
		(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof = int32(1)
	} else {
		zTerm = _sqlite3Fts5IterTerm(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter, bp+4)
		if (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm >= 0 {
			if **(**int32)(__ccgo_up(bp + 4)) < (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm {
				v1 = **(**int32)(__ccgo_up(bp + 4))
			} else {
				v1 = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm
			}
			nCmp = v1
			bCmp = libc.Xmemcmp(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FzLeTerm, zTerm, libc.Uint32FromInt32(nCmp))
			if bCmp < 0 || bCmp == 0 && (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm < **(**int32)(__ccgo_up(bp + 4)) {
				(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof = int32(1)
			}
		}
		_sqlite3Fts5BufferSet(tls, bp, pCsr+56, **(**int32)(__ccgo_up(bp + 4)), zTerm)
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Advance the cursor to the next row in the table.
//	*/
func _fts5VocabNextMethod(tls *libc.TLS, pCursor uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var bCmp, eDetail, iCol, ii1, nCmp, nCol, nPos, v2 int32
	var pCsr, pPos, pTab, zTerm uintptr
	var v3 Ti64
	var _ /* iOff at bp+16 */ int32
	var _ /* iPos at bp+8 */ Ti64
	var _ /* ii at bp+20 */ Tu32
	var _ /* nTerm at bp+4 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _, _, _, _ = bCmp, eDetail, iCol, ii1, nCmp, nCol, nPos, pCsr, pPos, pTab, zTerm, v2, v3
	pCsr = pCursor
	pTab = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(pCursor)).FpVtab
	nCol = (*TFts5Config)(unsafe.Pointer((*TFts5Table)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpFts5)).FpConfig)).FnCol
	**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5StructureTest(tls, (*TFts5Table)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpFts5)).FpIndex, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpStruct)
	if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
		return **(**int32)(__ccgo_up(bp))
	}
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).Frowid = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).Frowid + 1
	if (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType == int32(FTS5_VOCAB_INSTANCE) {
		return _fts5VocabInstanceNext(tls, pCsr)
	}
	if (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType == FTS5_VOCAB_COL {
		(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol + 1
		for {
			if !((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol < nCol) {
				break
			}
			if **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol)*8)) != 0 {
				break
			}
			goto _1
		_1:
			;
			(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol + 1
		}
	}
	if (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType != FTS5_VOCAB_COL || (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol >= nCol {
		if (*TFts5IndexIter)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)).FbEof != 0 {
			(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof = int32(1)
		} else {
			zTerm = _sqlite3Fts5IterTerm(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter, bp+4)
			if (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm >= 0 {
				if **(**int32)(__ccgo_up(bp + 4)) < (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm {
					v2 = **(**int32)(__ccgo_up(bp + 4))
				} else {
					v2 = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm
				}
				nCmp = v2
				bCmp = libc.Xmemcmp(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FzLeTerm, zTerm, libc.Uint32FromInt32(nCmp))
				if bCmp < 0 || bCmp == 0 && (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm < **(**int32)(__ccgo_up(bp + 4)) {
					(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof = int32(1)
					return SQLITE_OK
				}
			}
			_sqlite3Fts5BufferSet(tls, bp, pCsr+56, **(**int32)(__ccgo_up(bp + 4)), zTerm)
			libc.Xmemset(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt, 0, libc.Uint32FromInt32(nCol)*uint32(8))
			libc.Xmemset(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc, 0, libc.Uint32FromInt32(nCol)*uint32(8))
			(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol = 0
			for **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
				eDetail = (*TFts5Config)(unsafe.Pointer((*TFts5Table)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpFts5)).FpConfig)).FeDetail /* Position list */
				**(**Ti64)(__ccgo_up(bp + 8)) = 0                                                                                                           /* 64-bit position read from poslist */
				**(**int32)(__ccgo_up(bp + 16)) = 0                                                                                                         /* Current offset within position list */
				pPos = (*TFts5IndexIter)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)).FpData
				nPos = (*TFts5IndexIter)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)).FnData
				switch (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType {
				case int32(FTS5_VOCAB_ROW):
					/* Do not bother counting the number of instances if the "cnt"
					 ** column is not being read (according to colUsed).  */
					if eDetail == FTS5_DETAIL_FULL && (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FcolUsed&int32(0x04) != 0 {
						for **(**Ti64)(__ccgo_up(bp + 8)) < int64(nPos) {
							v3 = **(**Ti64)(__ccgo_up(bp + 8))
							**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) + 1
							**(**Tu32)(__ccgo_up(bp + 20)) = uint32(**(**Tu8)(__ccgo_up(pPos + uintptr(v3))))
							if **(**Tu32)(__ccgo_up(bp + 20))&uint32(0x80) != 0 {
								**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) - 1
								**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) + int64(_sqlite3Fts5GetVarint32(tls, pPos+uintptr(**(**Ti64)(__ccgo_up(bp + 8))), bp+20))
							}
							if **(**Tu32)(__ccgo_up(bp + 20)) == uint32(1) {
								/* New column in the position list */
								v3 = **(**Ti64)(__ccgo_up(bp + 8))
								**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) + 1
								**(**Tu32)(__ccgo_up(bp + 20)) = uint32(**(**Tu8)(__ccgo_up(pPos + uintptr(v3))))
								if **(**Tu32)(__ccgo_up(bp + 20))&uint32(0x80) != 0 {
									**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) - 1
									**(**Ti64)(__ccgo_up(bp + 8)) = **(**Ti64)(__ccgo_up(bp + 8)) + int64(_sqlite3Fts5GetVarint32(tls, pPos+uintptr(**(**Ti64)(__ccgo_up(bp + 8))), bp+20))
								}
							} else {
								/* An instance - increment pCsr->aCnt[] */
								**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt)) + 1
							}
						}
					}
					**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc)) + 1
				case FTS5_VOCAB_COL:
					if eDetail == FTS5_DETAIL_FULL {
						iCol = -int32(1)
						for 0 == _sqlite3Fts5PoslistNext64(tls, pPos, nPos, bp+16, bp+8) {
							ii1 = int32(**(**Ti64)(__ccgo_up(bp + 8)) >> libc.Int32FromInt32(32) & libc.Int64FromInt32(0x7FFFFFFF))
							if iCol != ii1 {
								if ii1 >= nCol {
									**(**int32)(__ccgo_up(bp)) = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
									break
								}
								**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr(ii1)*8)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr(ii1)*8)) + 1
								iCol = ii1
							}
							**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt + uintptr(ii1)*8)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt + uintptr(ii1)*8)) + 1
						}
					} else {
						if eDetail == int32(FTS5_DETAIL_COLUMNS) {
							for 0 == _sqlite3Fts5PoslistNext64(tls, pPos, nPos, bp+16, bp+8) {
								if **(**Ti64)(__ccgo_up(bp + 8)) >= int64(nCol) {
									**(**int32)(__ccgo_up(bp)) = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
									break
								}
								**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr(**(**Ti64)(__ccgo_up(bp + 8)))*8)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr(**(**Ti64)(__ccgo_up(bp + 8)))*8)) + 1
							}
						} else {
							**(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc)) = **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc)) + 1
						}
					}
				default:
					break
				}
				if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
					**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5IterNextScan(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)
				}
				if (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType == int32(FTS5_VOCAB_INSTANCE) {
					break
				}
				if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
					zTerm = _sqlite3Fts5IterTerm(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter, bp+4)
					if **(**int32)(__ccgo_up(bp + 4)) != (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).Fterm.Fn || **(**int32)(__ccgo_up(bp + 4)) > 0 && libc.Xmemcmp(tls, zTerm, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).Fterm.Fp, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4)))) != 0 {
						break
					}
					if (*TFts5IndexIter)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)).FbEof != 0 {
						break
					}
				}
			}
		}
	}
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK && (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof == 0 && (*TFts5VocabTable)(unsafe.Pointer(pTab)).FeType == FTS5_VOCAB_COL {
		for {
			if !((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol < nCol && **(**Ti64)(__ccgo_up((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc + uintptr((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol)*8)) == 0) {
				break
			}
			goto _5
		_5:
			;
			(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol = (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol + 1
		}
		if (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol == nCol {
			**(**int32)(__ccgo_up(bp)) = libc.Int32FromInt32(SQLITE_CORRUPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Restore cursor pCsr to the state it was in immediately after being
//	** created by the xOpen() method.
//	*/
func _fts5VocabResetCursor(tls *libc.TLS, pCsr uintptr) {
	var nCol int32
	_ = nCol
	nCol = (*TFts5Config)(unsafe.Pointer((*TFts5Table)(unsafe.Pointer((*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpFts5)).FpConfig)).FnCol
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).Frowid = 0
	_sqlite3Fts5IterClose(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter)
	_sqlite3Fts5StructureRelease(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpStruct)
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpStruct = uintptr(0)
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FpIter = uintptr(0)
	Xsqlite3_free(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FzLeTerm)
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FnLeTerm = -int32(1)
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FzLeTerm = uintptr(0)
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FbEof = 0
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiCol = 0
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiInstPos = 0
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FiInstOff = 0
	(*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FcolUsed = 0
	libc.Xmemset(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaCnt, 0, uint32(8)*libc.Uint32FromInt32(nCol))
	libc.Xmemset(tls, (*TFts5VocabCursor)(unsafe.Pointer(pCsr)).FaDoc, 0, uint32(8)*libc.Uint32FromInt32(nCol))
}

// C documentation
//
//	/*
//	** If the argument is a codepoint corresponding to a lowercase letter
//	** in the ASCII range with a diacritic added, return the codepoint
//	** of the ASCII letter only. For example, if passed 235 - "LATIN
//	** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
//	** E"). The resuls of passing a codepoint that corresponds to an
//	** uppercase letter are undefined.
//	*/
func _fts5_remove_diacritic(tls *libc.TLS, c int32, bComplex int32) (r int32) {
	var aChar [126]uint8
	var aDia [126]uint16
	var iHi, iLo, iRes, iTest, v1 int32
	var key uint32
	_, _, _, _, _, _, _, _ = aChar, aDia, iHi, iLo, iRes, iTest, key, v1
	aDia = [126]uint16{
		1:   uint16(1797),
		2:   uint16(1848),
		3:   uint16(1859),
		4:   uint16(1891),
		5:   uint16(1928),
		6:   uint16(1940),
		7:   uint16(1995),
		8:   uint16(2024),
		9:   uint16(2040),
		10:  uint16(2060),
		11:  uint16(2110),
		12:  uint16(2168),
		13:  uint16(2206),
		14:  uint16(2264),
		15:  uint16(2286),
		16:  uint16(2344),
		17:  uint16(2383),
		18:  uint16(2472),
		19:  uint16(2488),
		20:  uint16(2516),
		21:  uint16(2596),
		22:  uint16(2668),
		23:  uint16(2732),
		24:  uint16(2782),
		25:  uint16(2842),
		26:  uint16(2894),
		27:  uint16(2954),
		28:  uint16(2984),
		29:  uint16(3000),
		30:  uint16(3028),
		31:  uint16(3336),
		32:  uint16(3456),
		33:  uint16(3696),
		34:  uint16(3712),
		35:  uint16(3728),
		36:  uint16(3744),
		37:  uint16(3766),
		38:  uint16(3832),
		39:  uint16(3896),
		40:  uint16(3912),
		41:  uint16(3928),
		42:  uint16(3944),
		43:  uint16(3968),
		44:  uint16(4008),
		45:  uint16(4040),
		46:  uint16(4056),
		47:  uint16(4106),
		48:  uint16(4138),
		49:  uint16(4170),
		50:  uint16(4202),
		51:  uint16(4234),
		52:  uint16(4266),
		53:  uint16(4296),
		54:  uint16(4312),
		55:  uint16(4344),
		56:  uint16(4408),
		57:  uint16(4424),
		58:  uint16(4442),
		59:  uint16(4472),
		60:  uint16(4488),
		61:  uint16(4504),
		62:  uint16(6148),
		63:  uint16(6198),
		64:  uint16(6264),
		65:  uint16(6280),
		66:  uint16(6360),
		67:  uint16(6429),
		68:  uint16(6505),
		69:  uint16(6529),
		70:  uint16(61448),
		71:  uint16(61468),
		72:  uint16(61512),
		73:  uint16(61534),
		74:  uint16(61592),
		75:  uint16(61610),
		76:  uint16(61642),
		77:  uint16(61672),
		78:  uint16(61688),
		79:  uint16(61704),
		80:  uint16(61726),
		81:  uint16(61784),
		82:  uint16(61800),
		83:  uint16(61816),
		84:  uint16(61836),
		85:  uint16(61880),
		86:  uint16(61896),
		87:  uint16(61914),
		88:  uint16(61948),
		89:  uint16(61998),
		90:  uint16(62062),
		91:  uint16(62122),
		92:  uint16(62154),
		93:  uint16(62184),
		94:  uint16(62200),
		95:  uint16(62218),
		96:  uint16(62252),
		97:  uint16(62302),
		98:  uint16(62364),
		99:  uint16(62410),
		100: uint16(62442),
		101: uint16(62478),
		102: uint16(62536),
		103: uint16(62554),
		104: uint16(62584),
		105: uint16(62604),
		106: uint16(62640),
		107: uint16(62648),
		108: uint16(62656),
		109: uint16(62664),
		110: uint16(62730),
		111: uint16(62766),
		112: uint16(62830),
		113: uint16(62890),
		114: uint16(62924),
		115: uint16(62974),
		116: uint16(63032),
		117: uint16(63050),
		118: uint16(63082),
		119: uint16(63118),
		120: uint16(63182),
		121: uint16(63242),
		122: uint16(63274),
		123: uint16(63310),
		124: uint16(63368),
		125: uint16(63390),
	}
	aChar = [126]uint8{
		1:   uint8('a'),
		2:   uint8('c'),
		3:   uint8('e'),
		4:   uint8('i'),
		5:   uint8('n'),
		6:   uint8('o'),
		7:   uint8('u'),
		8:   uint8('y'),
		9:   uint8('y'),
		10:  uint8('a'),
		11:  uint8('c'),
		12:  uint8('d'),
		13:  uint8('e'),
		14:  uint8('e'),
		15:  uint8('g'),
		16:  uint8('h'),
		17:  uint8('i'),
		18:  uint8('j'),
		19:  uint8('k'),
		20:  uint8('l'),
		21:  uint8('n'),
		22:  uint8('o'),
		23:  uint8('r'),
		24:  uint8('s'),
		25:  uint8('t'),
		26:  uint8('u'),
		27:  uint8('u'),
		28:  uint8('w'),
		29:  uint8('y'),
		30:  uint8('z'),
		31:  uint8('o'),
		32:  uint8('u'),
		33:  uint8('a'),
		34:  uint8('i'),
		35:  uint8('o'),
		36:  uint8('u'),
		37:  libc.Uint8FromInt32(libc.Int32FromUint8('u') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		38:  libc.Uint8FromInt32(libc.Int32FromUint8('a') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		39:  uint8('g'),
		40:  uint8('k'),
		41:  uint8('o'),
		42:  libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		43:  uint8('j'),
		44:  uint8('g'),
		45:  uint8('n'),
		46:  libc.Uint8FromInt32(libc.Int32FromUint8('a') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		47:  uint8('a'),
		48:  uint8('e'),
		49:  uint8('i'),
		50:  uint8('o'),
		51:  uint8('r'),
		52:  uint8('u'),
		53:  uint8('s'),
		54:  uint8('t'),
		55:  uint8('h'),
		56:  uint8('a'),
		57:  uint8('e'),
		58:  libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		59:  uint8('o'),
		60:  libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		61:  uint8('y'),
		70:  uint8('a'),
		71:  uint8('b'),
		72:  libc.Uint8FromInt32(libc.Int32FromUint8('c') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		73:  uint8('d'),
		74:  uint8('d'),
		75:  libc.Uint8FromInt32(libc.Int32FromUint8('e') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		76:  uint8('e'),
		77:  libc.Uint8FromInt32(libc.Int32FromUint8('e') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		78:  uint8('f'),
		79:  uint8('g'),
		80:  uint8('h'),
		81:  uint8('h'),
		82:  uint8('i'),
		83:  libc.Uint8FromInt32(libc.Int32FromUint8('i') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		84:  uint8('k'),
		85:  uint8('l'),
		86:  libc.Uint8FromInt32(libc.Int32FromUint8('l') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		87:  uint8('l'),
		88:  uint8('m'),
		89:  uint8('n'),
		90:  libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		91:  uint8('p'),
		92:  uint8('r'),
		93:  libc.Uint8FromInt32(libc.Int32FromUint8('r') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		94:  uint8('r'),
		95:  uint8('s'),
		96:  libc.Uint8FromInt32(libc.Int32FromUint8('s') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		97:  uint8('t'),
		98:  uint8('u'),
		99:  libc.Uint8FromInt32(libc.Int32FromUint8('u') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		100: uint8('v'),
		101: uint8('w'),
		102: uint8('w'),
		103: uint8('x'),
		104: uint8('y'),
		105: uint8('z'),
		106: uint8('h'),
		107: uint8('t'),
		108: uint8('w'),
		109: uint8('y'),
		110: uint8('a'),
		111: libc.Uint8FromInt32(libc.Int32FromUint8('a') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		112: libc.Uint8FromInt32(libc.Int32FromUint8('a') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		113: libc.Uint8FromInt32(libc.Int32FromUint8('a') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		114: uint8('e'),
		115: libc.Uint8FromInt32(libc.Int32FromUint8('e') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		116: libc.Uint8FromInt32(libc.Int32FromUint8('e') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		117: uint8('i'),
		118: uint8('o'),
		119: libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		120: libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		121: libc.Uint8FromInt32(libc.Int32FromUint8('o') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		122: uint8('u'),
		123: libc.Uint8FromInt32(libc.Int32FromUint8('u') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		124: libc.Uint8FromInt32(libc.Int32FromUint8('u') | libc.Int32FromUint8(libc.Uint8FromInt32(0x80))),
		125: uint8('y'),
	}
	key = libc.Uint32FromInt32(c)<<int32(3) | uint32(0x00000007)
	iRes = 0
	iHi = libc.Int32FromUint32(libc.Uint32FromInt64(252)/libc.Uint32FromInt64(2) - libc.Uint32FromInt32(1))
	iLo = 0
	for iHi >= iLo {
		iTest = (iHi + iLo) / int32(2)
		if key >= uint32(aDia[iTest]) {
			iRes = iTest
			iLo = iTest + int32(1)
		} else {
			iHi = iTest - int32(1)
		}
	}
	if bComplex == 0 && libc.Int32FromUint8(aChar[iRes])&int32(0x80) != 0 {
		return c
	}
	if c > libc.Int32FromUint16(aDia[iRes])>>int32(3)+libc.Int32FromUint16(aDia[iRes])&int32(0x07) {
		v1 = c
	} else {
		v1 = libc.Int32FromUint8(aChar[iRes]) & int32(0x7F)
	}
	return v1
}

// C documentation
//
//	/*
//	** Perform a reduce action and the shift that must immediately
//	** follow the reduce.
//	**
//	** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
//	** access to the lookahead token (if any).  The fts5yyLookahead will be fts5YYNOCODE
//	** if the lookahead token has already been consumed.  As this procedure is
//	** only called from one place, optimizing compilers will in-line it, which
//	** means that the extra parameters have no performance impact.
//	*/
func _fts5yy_reduce(tls *libc.TLS, fts5yypParser uintptr, fts5yyruleno uint32, fts5yyLookahead int32, fts5yyLookaheadToken TFts5Token) (r uint8) {
	var fts5yyact uint8
	var fts5yygoto, fts5yysize int32
	var fts5yylhsminor Tfts5YYMINORTYPE
	var fts5yymsp, pParse uintptr
	_, _, _, _, _, _ = fts5yyact, fts5yygoto, fts5yylhsminor, fts5yymsp, fts5yysize, pParse /* Amount to pop the stack */
	pParse = (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).FpParse
	_ = fts5yyLookahead
	_ = fts5yyLookaheadToken
	fts5yymsp = (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos
	switch fts5yyruleno {
	case uint32(0):
		goto _1
	case uint32(1):
		goto _2
	case uint32(2):
		goto _3
	case uint32(3):
		goto _4
	case uint32(4):
		goto _5
	case uint32(5):
		goto _6
	case uint32(6):
		goto _7
	case uint32(7):
		goto _8
	case uint32(8):
		goto _9
	case uint32(9):
		goto _10
	case uint32(10):
		goto _11
	case uint32(11):
		goto _12
	case uint32(13):
		goto _13
	case uint32(12):
		goto _14
	case uint32(14):
		goto _15
	case uint32(15):
		goto _16
	case uint32(16):
		goto _17
	case uint32(17):
		goto _18
	case uint32(18):
		goto _19
	case uint32(19):
		goto _20
	case uint32(20):
		goto _21
	case uint32(21):
		goto _22
	case uint32(22):
		goto _23
	case uint32(23):
		goto _24
	case uint32(24):
		goto _25
	case uint32(25):
		goto _26
	case uint32(26):
		goto _27
	case uint32(27):
		goto _28
	default:
		goto _29
	}
	goto _30
_1:
	; /* input ::= expr */
	_sqlite3Fts5ParseFinished(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	goto _30
_2:
	; /* colset ::= MINUS LCP colsetlist RCP */
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(3))*12 + 4)) = _sqlite3Fts5ParseColsetInvert(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)))
	goto _30
_3:
	; /* colset ::= LCP colsetlist RCP */
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4))
	goto _30
_4:
	; /* colset ::= STRING */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseColset(tls, pParse, uintptr(0), fts5yymsp+4)
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_5:
	; /* colset ::= MINUS STRING */
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = _sqlite3Fts5ParseColset(tls, pParse, uintptr(0), fts5yymsp+4)
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = _sqlite3Fts5ParseColsetInvert(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)))
	goto _30
_6:
	; /* colsetlist ::= colsetlist STRING */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseColset(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)), fts5yymsp+4)
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_7:
	; /* colsetlist ::= STRING */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseColset(tls, pParse, uintptr(0), fts5yymsp+4)
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_8:
	; /* expr ::= expr AND expr */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNode(tls, pParse, int32(FTS5_AND), *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)), uintptr(0))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_9:
	; /* expr ::= expr OR expr */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNode(tls, pParse, int32(FTS5_OR), *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)), uintptr(0))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_10:
	; /* expr ::= expr NOT expr */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNode(tls, pParse, int32(FTS5_NOT), *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)), uintptr(0))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_11:
	; /* expr ::= colset COLON LP expr RP */
	_sqlite3Fts5ParseSetColset(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(4))*12 + 4)))
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(4))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_12:
	; /* expr ::= LP expr RP */
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4))
	goto _30
_14:
	; /* expr ::= exprlist */
_13:
	;
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = *(*uintptr)(unsafe.Pointer(fts5yymsp + 4))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_15:
	; /* exprlist ::= exprlist cnearset */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseImplicitAnd(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_16:
	; /* cnearset ::= nearset */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNode(tls, pParse, int32(FTS5_STRING), uintptr(0), uintptr(0), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_17:
	; /* cnearset ::= colset COLON nearset */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNode(tls, pParse, int32(FTS5_STRING), uintptr(0), uintptr(0), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	_sqlite3Fts5ParseSetColset(tls, pParse, *(*uintptr)(unsafe.Pointer(&fts5yylhsminor)), *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_18:
	; /* nearset ::= phrase */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNearset(tls, pParse, uintptr(0), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_19:
	; /* nearset ::= CARET phrase */
	_sqlite3Fts5ParseSetCaret(tls, *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = _sqlite3Fts5ParseNearset(tls, pParse, uintptr(0), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	goto _30
_20:
	; /* nearset ::= STRING LP nearphrases neardist_opt RP */
	_sqlite3Fts5ParseNear(tls, pParse, fts5yymsp+uintptr(-libc.Int32FromInt32(4))*12+4)
	_sqlite3Fts5ParseSetDistance(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4)), fts5yymsp+uintptr(-libc.Int32FromInt32(1))*12+4)
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(2))*12 + 4))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(4))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_21:
	; /* nearphrases ::= phrase */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNearset(tls, pParse, uintptr(0), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_22:
	; /* nearphrases ::= nearphrases phrase */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseNearset(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)), *(*uintptr)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_23:
	; /* neardist_opt ::= */
	*(*uintptr)(unsafe.Pointer(fts5yymsp + 1*12 + 4)) = uintptr(0)
	*(*int32)(unsafe.Pointer(fts5yymsp + 1*12 + 4 + 4)) = 0
	goto _30
_24:
	; /* neardist_opt ::= COMMA STRING */
	*(*TFts5Token)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = *(*TFts5Token)(unsafe.Pointer(fts5yymsp + 4))
	goto _30
_25:
	; /* phrase ::= phrase PLUS STRING star_opt */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseTerm(tls, pParse, *(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(3))*12 + 4)), fts5yymsp+uintptr(-libc.Int32FromInt32(1))*12+4, *(*int32)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(3))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_26:
	; /* phrase ::= STRING star_opt */
	*(*uintptr)(unsafe.Pointer(&fts5yylhsminor)) = _sqlite3Fts5ParseTerm(tls, pParse, uintptr(0), fts5yymsp+uintptr(-libc.Int32FromInt32(1))*12+4, *(*int32)(unsafe.Pointer(fts5yymsp + 4)))
	*(*uintptr)(unsafe.Pointer(fts5yymsp + uintptr(-libc.Int32FromInt32(1))*12 + 4)) = *(*uintptr)(unsafe.Pointer(&fts5yylhsminor))
	goto _30
_27:
	; /* star_opt ::= STAR */
	*(*int32)(unsafe.Pointer(fts5yymsp + 4)) = int32(1)
	goto _30
_28:
	; /* star_opt ::= */
	*(*int32)(unsafe.Pointer(fts5yymsp + 1*12 + 4)) = 0
	goto _30
_29:
	;
	goto _30
	/********** End reduce actions ************************************************/
_30:
	;
	fts5yygoto = libc.Int32FromUint8(_fts5yyRuleInfoLhs[fts5yyruleno])
	fts5yysize = int32(_fts5yyRuleInfoNRhs[fts5yyruleno])
	fts5yyact = _fts5yy_find_reduce_action(tls, (**(**Tfts5yyStackEntry)(__ccgo_up(fts5yymsp + uintptr(fts5yysize)*12))).Fstateno, libc.Uint8FromInt32(fts5yygoto))
	/* There are no SHIFTREDUCE actions on nonterminals because the table
	 ** generator has simplified them to pure REDUCE actions. */
	/* It is not possible for a REDUCE to be followed by an error */
	fts5yymsp = fts5yymsp + uintptr(fts5yysize+int32(1))*12
	(*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos = fts5yymsp
	(*Tfts5yyStackEntry)(unsafe.Pointer(fts5yymsp)).Fstateno = fts5yyact
	(*Tfts5yyStackEntry)(unsafe.Pointer(fts5yymsp)).Fmajor = libc.Uint8FromInt32(fts5yygoto)
	return fts5yyact
}

/*
** The following code executes when the parse fails
 */

// C documentation
//
//	/*
//	** Perform a shift action.
//	*/
func _fts5yy_shift(tls *libc.TLS, fts5yypParser uintptr, fts5yyNewState uint8, fts5yyMajor uint8, fts5yyMinor TFts5Token) {
	var fts5yytos uintptr
	_ = fts5yytos
	(*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos += 12
	fts5yytos = (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos
	if fts5yytos > (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yystackEnd {
		if int32(1) != 0 {
			(*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos -= 12
			_fts5yyStackOverflow(tls, fts5yypParser)
			return
		}
		fts5yytos = (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos
	}
	if libc.Int32FromUint8(fts5yyNewState) > int32(fts5YY_MAX_SHIFT) {
		fts5yyNewState = libc.Uint8FromInt32(int32(fts5yyNewState) + (libc.Int32FromInt32(fts5YY_MIN_REDUCE) - libc.Int32FromInt32(fts5YY_MIN_SHIFTREDUCE)))
	}
	(*Tfts5yyStackEntry)(unsafe.Pointer(fts5yytos)).Fstateno = fts5yyNewState
	(*Tfts5yyStackEntry)(unsafe.Pointer(fts5yytos)).Fmajor = fts5yyMajor
	*(*TFts5Token)(unsafe.Pointer(fts5yytos + 4)) = fts5yyMinor
}

// C documentation
//
//	/*
//	** The gatherSelectWindows() procedure and its helper routine
//	** gatherSelectWindowsCallback() are used to scan all the expressions
//	** an a newly duplicated SELECT statement and gather all of the Window
//	** objects found there, assembling them onto the linked list at Select->pWin.
//	*/
func _gatherSelectWindowsCallback(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pSelect, pWin uintptr
	_, _ = pSelect, pWin
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_FUNCTION) && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
		pSelect = *(*uintptr)(unsafe.Pointer(pWalker + 24))
		pWin = *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy))
		_sqlite3WindowLink(tls, pSelect, pWin)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** If pPoly is a polygon, compute its bounding box. Then:
//	**
//	**    (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
//	**    (2) otherwise, compute a GeoPoly for the bounding box and return the
//	**        new GeoPoly
//	**
//	** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
//	** the bounding box in aCoord and return a pointer to that GeoPoly.
//	*/
func _geopolyBBox(tls *libc.TLS, context uintptr, pPoly uintptr, aCoord uintptr, pRc uintptr) (r1 uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var mnX, mnY, mxX, mxY, v3 float32
	var p, pOut uintptr
	var r float64
	var _ /* ii at bp+0 */ int32
	_, _, _, _, _, _, _, _ = mnX, mnY, mxX, mxY, p, pOut, r, v3
	pOut = uintptr(0)
	if pPoly == uintptr(0) && aCoord != uintptr(0) {
		p = uintptr(0)
		mnX = *(*TRtreeValue)(unsafe.Pointer(aCoord))
		mxX = *(*TRtreeValue)(unsafe.Pointer(aCoord + 1*4))
		mnY = *(*TRtreeValue)(unsafe.Pointer(aCoord + 2*4))
		mxY = *(*TRtreeValue)(unsafe.Pointer(aCoord + 3*4))
		goto geopolyBboxFill
	} else {
		p = _geopolyFuncParam(tls, context, pPoly, pRc)
	}
	if !(p != 0) {
		goto _1
	}
	v3 = **(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(libc.Int32FromInt32(0)*libc.Int32FromInt32(2))*4))
	mxX = v3
	mnX = v3
	v3 = **(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(libc.Int32FromInt32(0)*libc.Int32FromInt32(2)+libc.Int32FromInt32(1))*4))
	mxY = v3
	mnY = v3
	**(**int32)(__ccgo_up(bp)) = int32(1)
	for {
		if !(**(**int32)(__ccgo_up(bp)) < (*TGeoPoly)(unsafe.Pointer(p)).FnVertex) {
			break
		}
		r = float64(**(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(**(**int32)(__ccgo_up(bp))*int32(2))*4)))
		if r < float64(mnX) {
			mnX = float32(r)
		} else {
			if r > float64(mxX) {
				mxX = float32(r)
			}
		}
		r = float64(**(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(**(**int32)(__ccgo_up(bp))*int32(2)+int32(1))*4)))
		if r < float64(mnY) {
			mnY = float32(r)
		} else {
			if r > float64(mxY) {
				mxY = float32(r)
			}
		}
		goto _5
	_5:
		;
		**(**int32)(__ccgo_up(bp)) = **(**int32)(__ccgo_up(bp)) + 1
	}
	if pRc != 0 {
		**(**int32)(__ccgo_up(pRc)) = SQLITE_OK
	}
	if !(aCoord == uintptr(0)) {
		goto _6
	}
	goto geopolyBboxFill
geopolyBboxFill:
	;
	pOut = Xsqlite3_realloc64(tls, p, uint64(libc.Uint32FromInt64(40)+libc.Uint32FromInt64(4)*libc.Uint32FromInt32(2)*libc.Uint32FromInt32(libc.Int32FromInt32(4)-libc.Int32FromInt32(4))))
	if pOut == uintptr(0) {
		Xsqlite3_free(tls, p)
		if context != 0 {
			Xsqlite3_result_error_nomem(tls, context)
		}
		if pRc != 0 {
			**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_NOMEM)
		}
		return uintptr(0)
	}
	(*TGeoPoly)(unsafe.Pointer(pOut)).FnVertex = int32(4)
	**(**int32)(__ccgo_up(bp)) = int32(1)
	**(**uint8)(__ccgo_up(pOut + 4)) = **(**uint8)(__ccgo_up(bp))
	**(**uint8)(__ccgo_up(pOut + 4 + 1)) = uint8(0)
	**(**uint8)(__ccgo_up(pOut + 4 + 2)) = uint8(0)
	**(**uint8)(__ccgo_up(pOut + 4 + 3)) = uint8(4)
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(0)*libc.Int32FromInt32(2))*4)) = mnX
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(0)*libc.Int32FromInt32(2)+libc.Int32FromInt32(1))*4)) = mnY
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(1)*libc.Int32FromInt32(2))*4)) = mxX
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(1)*libc.Int32FromInt32(2)+libc.Int32FromInt32(1))*4)) = mnY
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(2)*libc.Int32FromInt32(2))*4)) = mxX
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(2)*libc.Int32FromInt32(2)+libc.Int32FromInt32(1))*4)) = mxY
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(3)*libc.Int32FromInt32(2))*4)) = mnX
	**(**TGeoCoord)(__ccgo_up(pOut + 8 + uintptr(libc.Int32FromInt32(3)*libc.Int32FromInt32(2)+libc.Int32FromInt32(1))*4)) = mxY
	goto _7
_6:
	;
	Xsqlite3_free(tls, p)
	*(*TRtreeValue)(unsafe.Pointer(aCoord)) = mnX
	*(*TRtreeValue)(unsafe.Pointer(aCoord + 1*4)) = mxX
	*(*TRtreeValue)(unsafe.Pointer(aCoord + 2*4)) = mnY
	*(*TRtreeValue)(unsafe.Pointer(aCoord + 3*4)) = mxY
_7:
	;
	goto _2
_1:
	;
	if aCoord != 0 {
		libc.Xmemset(tls, aCoord, 0, libc.Uint32FromInt64(4)*libc.Uint32FromInt32(4))
	}
_2:
	;
	return pOut
}

// C documentation
//
//	/*
//	** GEOPOLY virtual table module xColumn method.
//	*/
func _geopolyColumn(tls *libc.TLS, cur uintptr, ctx uintptr, i int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var p, pCsr, pNode, pRtree uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _, _ = p, pCsr, pNode, pRtree
	pRtree = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(cur)).FpVtab
	pCsr = cur
	p = _rtreeSearchPointFirst(tls, pCsr)
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	pNode = _rtreeNodeOfFirstSearchPoint(tls, pCsr, bp)
	if **(**int32)(__ccgo_up(bp)) != 0 {
		return **(**int32)(__ccgo_up(bp))
	}
	if p == uintptr(0) {
		return SQLITE_OK
	}
	if i == 0 && Xsqlite3_vtab_nochange(tls, ctx) != 0 {
		return SQLITE_OK
	}
	if i <= libc.Int32FromUint16((*TRtree)(unsafe.Pointer(pRtree)).FnAux) {
		if !((*TRtreeCursor)(unsafe.Pointer(pCsr)).FbAuxValid != 0) {
			if (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux == uintptr(0) {
				**(**int32)(__ccgo_up(bp)) = Xsqlite3_prepare_v3(tls, (*TRtree)(unsafe.Pointer(pRtree)).Fdb, (*TRtree)(unsafe.Pointer(pRtree)).FzReadAuxSql, -int32(1), uint32(0), pCsr+36, uintptr(0))
				if **(**int32)(__ccgo_up(bp)) != 0 {
					return **(**int32)(__ccgo_up(bp))
				}
			}
			Xsqlite3_bind_int64(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux, int32(1), _nodeGetRowid(tls, pRtree, pNode, libc.Int32FromUint8((*TRtreeSearchPoint)(unsafe.Pointer(p)).FiCell)))
			**(**int32)(__ccgo_up(bp)) = Xsqlite3_step(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux)
			if **(**int32)(__ccgo_up(bp)) == int32(SQLITE_ROW) {
				(*TRtreeCursor)(unsafe.Pointer(pCsr)).FbAuxValid = uint8(1)
			} else {
				Xsqlite3_reset(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux)
				if **(**int32)(__ccgo_up(bp)) == int32(SQLITE_DONE) {
					**(**int32)(__ccgo_up(bp)) = SQLITE_OK
				}
				return **(**int32)(__ccgo_up(bp))
			}
		}
		Xsqlite3_result_value(tls, ctx, Xsqlite3_column_value(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux, i+int32(2)))
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Given a function parameter, try to interpret it as a polygon, either
//	** in the binary format or JSON text.  Compute a GeoPoly object and
//	** return a pointer to that object.  Or if the input is not a well-formed
//	** polygon, put an error message in sqlite3_context and return NULL.
//	*/
func _geopolyFuncParam(tls *libc.TLS, pCtx uintptr, pVal uintptr, pRc uintptr) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a, p, zJson, v4 uintptr
	var ii, nByte, nVertex, v1 int32
	var v2 bool
	var _ /* x at bp+0 */ int32
	_, _, _, _, _, _, _, _, _ = a, ii, nByte, nVertex, p, zJson, v1, v2, v4
	p = uintptr(0)
	if v2 = Xsqlite3_value_type(tls, pVal) == int32(SQLITE_BLOB); v2 {
		v1 = Xsqlite3_value_bytes(tls, pVal)
		nByte = v1
	}
	if v2 && v1 >= libc.Int32FromUint32(libc.Uint32FromInt32(4)+libc.Uint32FromInt32(6)*libc.Uint32FromInt64(4)) {
		a = Xsqlite3_value_blob(tls, pVal)
		if a == uintptr(0) {
			if pCtx != 0 {
				Xsqlite3_result_error_nomem(tls, pCtx)
			}
			return uintptr(0)
		}
		nVertex = libc.Int32FromUint8(**(**uint8)(__ccgo_up(a + 1)))<<int32(16) + libc.Int32FromUint8(**(**uint8)(__ccgo_up(a + 2)))<<int32(8) + libc.Int32FromUint8(**(**uint8)(__ccgo_up(a + 3)))
		if (libc.Int32FromUint8(**(**uint8)(__ccgo_up(a))) == 0 || libc.Int32FromUint8(**(**uint8)(__ccgo_up(a))) == int32(1)) && libc.Uint32FromInt32(nVertex*int32(2))*uint32(4)+uint32(4) == libc.Uint32FromInt32(nByte) {
			p = Xsqlite3_malloc64(tls, uint64(uint32(40)+libc.Uint32FromInt32((nVertex-int32(1))*int32(2))*uint32(4)))
			if p == uintptr(0) {
				if pRc != 0 {
					**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_NOMEM)
				}
				if pCtx != 0 {
					Xsqlite3_result_error_nomem(tls, pCtx)
				}
			} else {
				**(**int32)(__ccgo_up(bp)) = int32(1)
				(*TGeoPoly)(unsafe.Pointer(p)).FnVertex = nVertex
				libc.Xmemcpy(tls, p+4, a, libc.Uint32FromInt32(nByte))
				if libc.Int32FromUint8(**(**uint8)(__ccgo_up(a))) != libc.Int32FromUint8(**(**uint8)(__ccgo_up(bp))) {
					ii = 0
					for {
						if !(ii < nVertex) {
							break
						}
						_geopolySwab32(tls, p+8+uintptr(ii*int32(2))*4)
						_geopolySwab32(tls, p+8+uintptr(ii*int32(2)+int32(1))*4)
						goto _3
					_3:
						;
						ii = ii + 1
					}
					v4 = p + 4
					*(*uint8)(unsafe.Pointer(v4)) = uint8(int32(*(*uint8)(unsafe.Pointer(v4))) ^ libc.Int32FromInt32(1))
				}
			}
		}
		if pRc != 0 {
			**(**int32)(__ccgo_up(pRc)) = SQLITE_OK
		}
		return p
	} else {
		if Xsqlite3_value_type(tls, pVal) == int32(SQLITE_TEXT) {
			zJson = Xsqlite3_value_text(tls, pVal)
			if zJson == uintptr(0) {
				if pRc != 0 {
					**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_NOMEM)
				}
				return uintptr(0)
			}
			return _geopolyParseJson(tls, zJson, pRc)
		} else {
			if pRc != 0 {
				**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_ERROR)
			}
			return uintptr(0)
		}
	}
	return r
}

// C documentation
//
//	/*
//	** Function:   geopoly_regular(X,Y,R,N)
//	**
//	** Construct a simple, convex, regular polygon centered at X, Y
//	** with circumradius R and with N sides.
//	*/
func _geopolyRegularFunc(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var n int32
	var p uintptr
	var r, rAngle, x, y float64
	var _ /* i at bp+0 */ int32
	_, _, _, _, _, _ = n, p, r, rAngle, x, y
	x = Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(argv)))
	y = Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
	r = Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(argv + 2*4)))
	n = Xsqlite3_value_int(tls, **(**uintptr)(__ccgo_up(argv + 3*4)))
	_ = argc
	if n < int32(3) || r <= float64(0) {
		return
	}
	if n > int32(1000) {
		n = int32(1000)
	}
	p = Xsqlite3_malloc64(tls, uint64(uint32(40)+libc.Uint32FromInt32((n-int32(1))*int32(2))*uint32(4)))
	if p == uintptr(0) {
		Xsqlite3_result_error_nomem(tls, context)
		return
	}
	**(**int32)(__ccgo_up(bp)) = int32(1)
	**(**uint8)(__ccgo_up(p + 4)) = **(**uint8)(__ccgo_up(bp))
	**(**uint8)(__ccgo_up(p + 4 + 1)) = uint8(0)
	**(**uint8)(__ccgo_up(p + 4 + 2)) = libc.Uint8FromInt32(n >> int32(8) & int32(0xff))
	**(**uint8)(__ccgo_up(p + 4 + 3)) = libc.Uint8FromInt32(n & int32(0xff))
	**(**int32)(__ccgo_up(bp)) = 0
	for {
		if !(**(**int32)(__ccgo_up(bp)) < n) {
			break
		}
		rAngle = float64(float64(libc.Float64FromFloat64(2)*libc.Float64FromFloat64(3.141592653589793))*float64(**(**int32)(__ccgo_up(bp)))) / float64(n)
		**(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(**(**int32)(__ccgo_up(bp))*int32(2))*4)) = float32(x - float64(r*_geopolySine(tls, rAngle-float64(libc.Float64FromFloat64(0.5)*libc.Float64FromFloat64(3.141592653589793)))))
		**(**TGeoCoord)(__ccgo_up(p + 8 + uintptr(**(**int32)(__ccgo_up(bp))*int32(2)+int32(1))*4)) = float32(y + float64(r*_geopolySine(tls, rAngle)))
		goto _1
	_1:
		;
		**(**int32)(__ccgo_up(bp)) = **(**int32)(__ccgo_up(bp)) + 1
	}
	Xsqlite3_result_blob(tls, context, p+4, int32(4)+int32(8)*n, uintptr(-libc.Int32FromInt32(1)))
	Xsqlite3_free(tls, p)
}

// C documentation
//
//	/*
//	** Given the page number of an overflow page in the database (parameter
//	** ovfl), this function finds the page number of the next page in the
//	** linked list of overflow pages. If possible, it uses the auto-vacuum
//	** pointer-map data instead of reading the content of page ovfl to do so.
//	**
//	** If an error occurs an SQLite error code is returned. Otherwise:
//	**
//	** The page number of the next overflow page in the linked list is
//	** written to *pPgnoNext. If page ovfl is the last page in its linked
//	** list, *pPgnoNext is set to zero.
//	**
//	** If ppPage is not NULL, and a reference to the MemPage object corresponding
//	** to page number pOvfl was obtained, then *ppPage is set to point to that
//	** reference. It is the responsibility of the caller to call releasePage()
//	** on *ppPage to free the reference. In no reference was obtained (because
//	** the pointer-map was used to obtain the value for *pPgnoNext), then
//	** *ppPage is set to zero.
//	*/
func _getOverflowPage(tls *libc.TLS, pBt uintptr, ovfl TPgno, ppPage uintptr, pPgnoNext uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iGuess, next TPgno
	var rc, v1 int32
	var _ /* eType at bp+8 */ Tu8
	var _ /* pPage at bp+0 */ uintptr
	var _ /* pgno at bp+4 */ TPgno
	_, _, _, _ = iGuess, next, rc, v1
	next = uint32(0)
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	rc = SQLITE_OK
	/* Try to find the next page in the overflow list using the
	 ** autovacuum pointer-map pages. Guess that the next page in
	 ** the overflow list is page number (ovfl+1). If that guess turns
	 ** out to be wrong, fall back to loading the data of page
	 ** number ovfl to determine the next page number.
	 */
	if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
		iGuess = ovfl + uint32(1)
		for _ptrmapPageno(tls, pBt, iGuess) == iGuess || iGuess == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
			iGuess = iGuess + 1
		}
		if iGuess <= _btreePagecount(tls, pBt) {
			rc = _ptrmapGet(tls, pBt, iGuess, bp+8, bp+4)
			if rc == SQLITE_OK && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp + 8))) == int32(PTRMAP_OVERFLOW2) && **(**TPgno)(__ccgo_up(bp + 4)) == ovfl {
				next = iGuess
				rc = int32(SQLITE_DONE)
			}
		}
	}
	if rc == SQLITE_OK {
		if ppPage == uintptr(0) {
			v1 = int32(PAGER_GET_READONLY)
		} else {
			v1 = 0
		}
		rc = _btreeGetPage(tls, pBt, ovfl, bp, v1)
		if rc == SQLITE_OK {
			next = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaData)
		}
	}
	**(**TPgno)(__ccgo_up(pPgnoNext)) = next
	if ppPage != 0 {
		**(**uintptr)(__ccgo_up(ppPage)) = **(**uintptr)(__ccgo_up(bp))
	} else {
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
	}
	if rc == int32(SQLITE_DONE) {
		v1 = SQLITE_OK
	} else {
		v1 = rc
	}
	return v1
}

// C documentation
//
//	/* The page getter for when memory-mapped I/O is enabled */
func _getPageMMap(tls *libc.TLS, pPager uintptr, pgno TPgno, ppPage uintptr, flags int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var bMmapOk, rc int32
	var _ /* iFrame at bp+4 */ Tu32
	var _ /* pData at bp+8 */ uintptr
	var _ /* pPg at bp+0 */ uintptr
	_, _ = bMmapOk, rc
	rc = SQLITE_OK
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	**(**Tu32)(__ccgo_up(bp + 4)) = uint32(0) /* Frame to read from WAL file */
	/* It is acceptable to use a read-only (mmap) page for any page except
	 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
	 ** flag was specified by the caller. And so long as the db is not a
	 ** temporary or in-memory database.  */
	bMmapOk = libc.BoolInt32(pgno > uint32(1) && (libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) == int32(PAGER_READER) || flags&int32(PAGER_GET_READONLY) != 0))
	/* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
	 ** allows the compiler optimizer to reuse the results of the "pgno>1"
	 ** test in the previous statement, and avoid testing pgno==0 in the
	 ** common case where pgno is large. */
	if pgno <= uint32(1) && pgno == uint32(0) {
		return _sqlite3CorruptError(tls, int32(65348))
	}
	if bMmapOk != 0 && (*TPager)(unsafe.Pointer(pPager)).FpWal != uintptr(0) {
		rc = _sqlite3WalFindFrame(tls, (*TPager)(unsafe.Pointer(pPager)).FpWal, pgno, bp+4)
		if rc != SQLITE_OK {
			**(**uintptr)(__ccgo_up(ppPage)) = uintptr(0)
			return rc
		}
	}
	if bMmapOk != 0 && **(**Tu32)(__ccgo_up(bp + 4)) == uint32(0) {
		**(**uintptr)(__ccgo_up(bp + 8)) = uintptr(0)
		rc = _sqlite3OsFetch(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, libc.Int64FromUint32(pgno-libc.Uint32FromInt32(1))*(*TPager)(unsafe.Pointer(pPager)).FpageSize, int32((*TPager)(unsafe.Pointer(pPager)).FpageSize), bp+8)
		if rc == SQLITE_OK && **(**uintptr)(__ccgo_up(bp + 8)) != 0 {
			if libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) > int32(PAGER_READER) || (*TPager)(unsafe.Pointer(pPager)).FtempFile != 0 {
				**(**uintptr)(__ccgo_up(bp)) = _sqlite3PagerLookup(tls, pPager, pgno)
			}
			if **(**uintptr)(__ccgo_up(bp)) == uintptr(0) {
				rc = _pagerAcquireMapPage(tls, pPager, pgno, **(**uintptr)(__ccgo_up(bp + 8)), bp)
			} else {
				_sqlite3OsUnfetch(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, libc.Int64FromUint32(pgno-libc.Uint32FromInt32(1))*(*TPager)(unsafe.Pointer(pPager)).FpageSize, **(**uintptr)(__ccgo_up(bp + 8)))
			}
			if **(**uintptr)(__ccgo_up(bp)) != 0 {
				**(**uintptr)(__ccgo_up(ppPage)) = **(**uintptr)(__ccgo_up(bp))
				return SQLITE_OK
			}
		}
		if rc != SQLITE_OK {
			**(**uintptr)(__ccgo_up(ppPage)) = uintptr(0)
			return rc
		}
	}
	return _getPageNormal(tls, pPager, pgno, ppPage, flags)
}

func _groupConcatInverse(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	var nVS int32
	var pGCC uintptr
	_, _ = nVS, pGCC
	_ = argc /* Suppress unused parameter warning */
	if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(argv))) == int32(SQLITE_NULL) {
		return
	}
	pGCC = Xsqlite3_aggregate_context(tls, context, int32(36))
	/* pGCC is always non-NULL since groupConcatStep() will have always
	 ** run first to initialize it */
	if pGCC != 0 { /* Number of characters to remove */
		/* Must call sqlite3_value_text() to convert the argument into text prior
		 ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
		Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
		nVS = Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(argv)))
		**(**int32)(__ccgo_up(pGCC + 24)) -= int32(1)
		if (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths != uintptr(0) {
			if (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FnAccum > 0 {
				nVS = nVS + **(**int32)(__ccgo_up((*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths))
				libc.Xmemmove(tls, (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths, (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths+uintptr(1)*4, libc.Uint32FromInt32((*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FnAccum-libc.Int32FromInt32(1))*uint32(4))
			}
		} else {
			/* If removing single accumulated string, harmlessly over-do. */
			nVS = nVS + (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FnFirstSepLength
		}
		if nVS >= libc.Int32FromUint32((*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FnChar) {
			(*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FnChar = uint32(0)
		} else {
			(*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FnChar -= libc.Uint32FromInt32(nVS)
			libc.Xmemmove(tls, (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FzText, (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FzText+uintptr(nVS), (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FnChar)
		}
		if (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FnChar == uint32(0) {
			(*TGroupConcatCtx)(unsafe.Pointer(pGCC)).Fstr.FmxAlloc = uint32(0)
			Xsqlite3_free(tls, (*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths)
			(*TGroupConcatCtx)(unsafe.Pointer(pGCC)).FpnSepLengths = uintptr(0)
		}
	}
}

// C documentation
//
//	/*
//	** Grow the db->aVTrans[] array so that there is room for at least one
//	** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
//	*/
func _growVTrans(tls *libc.TLS, db uintptr) (r int32) {
	var ARRAY_INCR int32
	var aVTrans uintptr
	var nBytes Tsqlite3_int64
	_, _, _ = ARRAY_INCR, aVTrans, nBytes
	ARRAY_INCR = int32(5)
	/* Grow the sqlite3.aVTrans array if required */
	if (*Tsqlite3)(unsafe.Pointer(db)).FnVTrans%ARRAY_INCR == 0 {
		nBytes = int64(4) * (int64((*Tsqlite3)(unsafe.Pointer(db)).FnVTrans) + int64(ARRAY_INCR))
		aVTrans = _sqlite3DbRealloc(tls, db, (*Tsqlite3)(unsafe.Pointer(db)).FaVTrans, libc.Uint64FromInt64(nBytes))
		if !(aVTrans != 0) {
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, aVTrans+uintptr((*Tsqlite3)(unsafe.Pointer(db)).FnVTrans)*4, 0, uint32(4)*libc.Uint32FromInt32(ARRAY_INCR))
		(*Tsqlite3)(unsafe.Pointer(db)).FaVTrans = aVTrans
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** sqlite3WalkExpr() callback used by havingToWhere().
//	**
//	** If the node passed to the callback is a TK_AND node, return
//	** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
//	**
//	** Otherwise, return WRC_Prune. In this case, also check if the
//	** sub-expression matches the criteria for being moved to the WHERE
//	** clause. If so, add it to the WHERE clause and replace the sub-expression
//	** within the HAVING expression with a constant "1".
//	*/
func _havingToWhereExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var db, pNew, pS, pWhere uintptr
	var t TExpr
	_, _, _, _, _ = db, pNew, pS, pWhere, t
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_AND) {
		pS = *(*uintptr)(unsafe.Pointer(pWalker + 24))
		/* This routine is called before the HAVING clause of the current
		 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
		 ** here, it indicates that the expression is a correlated reference to a
		 ** column from an outer aggregate query, or an aggregate function that
		 ** belongs to an outer query. Do not move the expression to the WHERE
		 ** clause in this obscure case, as doing so may corrupt the outer Select
		 ** statements AggInfo structure.  */
		if _sqlite3ExprIsConstantOrGroupBy(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, pExpr, (*TSelect)(unsafe.Pointer(pS)).FpGroupBy) != 0 && libc.BoolInt32((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_IsFalse)) == uint32(EP_IsFalse)) == 0 && (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo == uintptr(0) {
			db = (*TParse)(unsafe.Pointer((*TWalker)(unsafe.Pointer(pWalker)).FpParse)).Fdb
			pNew = _sqlite3ExprInt32(tls, db, int32(1))
			if pNew != 0 {
				pWhere = (*TSelect)(unsafe.Pointer(pS)).FpWhere
				t = **(**TExpr)(__ccgo_up(pNew))
				**(**TExpr)(__ccgo_up(pNew)) = **(**TExpr)(__ccgo_up(pExpr))
				**(**TExpr)(__ccgo_up(pExpr)) = t
				pNew = _sqlite3ExprAnd(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, pWhere, pNew)
				(*TSelect)(unsafe.Pointer(pS)).FpWhere = pNew
				(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(1)
			}
		}
		return int32(WRC_Prune)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
//	** If the expression node requires that the table at pWalker->iCur
//	** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
//	**
//	** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
//	** behalf of a RIGHT JOIN (or FULL JOIN).  That makes a difference when
//	** evaluating terms in the ON clause of an inner join.
//	**
//	** This routine controls an optimization.  False positives (setting
//	** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
//	** (never setting pWalker->eCode) is a harmless missed optimization.
//	*/
func _impliesNotNullRow(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pLeft, pRight uintptr
	_, _ = pLeft, pRight
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0) {
		return int32(WRC_Prune)
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_InnerON)) != uint32(0) && (*TWalker)(unsafe.Pointer(pWalker)).FmWFlags != 0 {
		/* If iCur is used in an inner-join ON clause to the left of a
		 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
		 ** But it is difficult to check for that condition precisely.
		 ** To keep things simple, any use of iCur from any inner-join is
		 ** ignored while attempting to simplify a RIGHT JOIN. */
		return int32(WRC_Prune)
	}
	switch libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) {
	case int32(TK_ISNOT):
		fallthrough
	case int32(TK_ISNULL):
		fallthrough
	case int32(TK_NOTNULL):
		fallthrough
	case int32(TK_IS):
		fallthrough
	case int32(TK_VECTOR):
		fallthrough
	case int32(TK_FUNCTION):
		fallthrough
	case int32(TK_TRUTH):
		fallthrough
	case int32(TK_CASE):
		return int32(WRC_Prune)
	case int32(TK_COLUMN):
		if *(*int32)(unsafe.Pointer(pWalker + 24)) == (*TExpr)(unsafe.Pointer(pExpr)).FiTable {
			(*TWalker)(unsafe.Pointer(pWalker)).FeCode = uint16(1)
			return int32(WRC_Abort)
		}
		return int32(WRC_Prune)
	case int32(TK_OR):
		fallthrough
	case int32(TK_AND):
		/* Both sides of an AND or OR must separately imply non-null-row.
		 ** Consider these cases:
		 **    1.  NOT (x AND y)
		 **    2.  x OR y
		 ** If only one of x or y is non-null-row, then the overall expression
		 ** can be true if the other arm is false (case 1) or true (case 2).
		 */
		_bothImplyNotNullRow(tls, pWalker, (*TExpr)(unsafe.Pointer(pExpr)).FpLeft, (*TExpr)(unsafe.Pointer(pExpr)).FpRight)
		return int32(WRC_Prune)
	case int32(TK_IN):
		/* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
		 ** both of which can be true.  But apart from these cases, if
		 ** the left-hand side of the IN is NULL then the IN itself will be
		 ** NULL. */
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&uint32(EP_xIsSelect) == uint32(0) && (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FnExpr > 0 {
			_sqlite3WalkExpr(tls, pWalker, (*TExpr)(unsafe.Pointer(pExpr)).FpLeft)
		}
		return int32(WRC_Prune)
	case int32(TK_BETWEEN):
		/* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
		 ** both y and z must be non-null row */
		_sqlite3WalkExpr(tls, pWalker, (*TExpr)(unsafe.Pointer(pExpr)).FpLeft)
		_bothImplyNotNullRow(tls, pWalker, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8))).FpExpr, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8 + 1*20))).FpExpr)
		return int32(WRC_Prune)
		/* Virtual tables are allowed to use constraints like x=NULL.  So
		 ** a term of the form x=y does not prove that y is not null if x
		 ** is the column of a virtual table */
		fallthrough
	case int32(TK_EQ):
		fallthrough
	case int32(TK_NE):
		fallthrough
	case int32(TK_LT):
		fallthrough
	case int32(TK_LE):
		fallthrough
	case int32(TK_GT):
		fallthrough
	case int32(TK_GE):
		pLeft = (*TExpr)(unsafe.Pointer(pExpr)).FpLeft
		pRight = (*TExpr)(unsafe.Pointer(pExpr)).FpRight
		/* The y.pTab=0 assignment in wherecode.c always happens after the
		 ** impliesNotNullRow() test */
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pLeft)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(pLeft)).Fy.FpTab != uintptr(0) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pLeft)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pRight)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(pRight)).Fy.FpTab != uintptr(0) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pRight)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB) {
			return int32(WRC_Prune)
		}
		fallthrough
	default:
		return WRC_Continue
	}
	return r
}

// C documentation
//
//	/*
//	** Walk the expression tree pExpr and increase the aggregate function
//	** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
//	** This needs to occur when copying a TK_AGG_FUNCTION node from an
//	** outer query into an inner subquery.
//	**
//	** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
//	** is a helper function - a callback for the tree walker.
//	**
//	** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
//	*/
func _incrAggDepth(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_FUNCTION) {
		v1 = pExpr + 2
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) + *(*int32)(unsafe.Pointer(pWalker + 24)))
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Perform a single step of an incremental-vacuum. If successful, return
//	** SQLITE_OK. If there is no work to do (and therefore no point in
//	** calling this function again), return SQLITE_DONE. Or, if an error
//	** occurs, return some other error code.
//	**
//	** More specifically, this function attempts to re-organize the database so
//	** that the last page of the file currently in use is no longer in use.
//	**
//	** Parameter nFin is the number of pages that this database would contain
//	** were this function called until it returns SQLITE_DONE.
//	**
//	** If the bCommit parameter is non-zero, this function assumes that the
//	** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
//	** or an error. bCommit is passed true for an auto-vacuum-on-commit
//	** operation, or false for an incremental vacuum.
//	*/
func _incrVacuumStep(tls *libc.TLS, pBt uintptr, nFin TPgno, iLastPg TPgno, bCommit int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var dbSize, iNear, nFreeList TPgno
	var eMode Tu8
	var rc int32
	var _ /* eType at bp+0 */ Tu8
	var _ /* iFreePg at bp+16 */ TPgno
	var _ /* iFreePg at bp+8 */ TPgno
	var _ /* iPtrPage at bp+4 */ TPgno
	var _ /* pFreePg at bp+12 */ uintptr
	var _ /* pFreePg at bp+24 */ uintptr
	var _ /* pLastPg at bp+20 */ uintptr
	_, _, _, _, _ = dbSize, eMode, iNear, nFreeList, rc
	if !(_ptrmapPageno(tls, pBt, iLastPg) == iLastPg) && iLastPg != libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) {
		nFreeList = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData+36)
		if nFreeList == uint32(0) {
			return int32(SQLITE_DONE)
		}
		rc = _ptrmapGet(tls, pBt, iLastPg, bp, bp+4)
		if rc != SQLITE_OK {
			return rc
		}
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp))) == int32(PTRMAP_ROOTPAGE) {
			return _sqlite3CorruptError(tls, int32(77285))
		}
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(bp))) == int32(PTRMAP_FREEPAGE) {
			if bCommit == 0 {
				rc = _allocateBtreePage(tls, pBt, bp+12, bp+8, iLastPg, uint8(BTALLOC_EXACT))
				if rc != SQLITE_OK {
					return rc
				}
				_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 12)))
			}
		} else {
			eMode = uint8(BTALLOC_ANY) /* Mode parameter for allocateBtreePage() */
			iNear = uint32(0)          /* nearby parameter for allocateBtreePage() */
			rc = _btreeGetPage(tls, pBt, iLastPg, bp+20, 0)
			if rc != SQLITE_OK {
				return rc
			}
			/* If bCommit is zero, this loop runs exactly once and page pLastPg
			 ** is swapped with the first free page pulled off the free list.
			 **
			 ** On the other hand, if bCommit is greater than zero, then keep
			 ** looping until a free-page located within the first nFin pages
			 ** of the file is found.
			 */
			if bCommit == 0 {
				eMode = uint8(BTALLOC_LE)
				iNear = nFin
			}
			for cond := true; cond; cond = bCommit != 0 && **(**TPgno)(__ccgo_up(bp + 16)) > nFin {
				dbSize = _btreePagecount(tls, pBt)
				rc = _allocateBtreePage(tls, pBt, bp+24, bp+16, iNear, eMode)
				if rc != SQLITE_OK {
					_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 20)))
					return rc
				}
				_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 24)))
				if **(**TPgno)(__ccgo_up(bp + 16)) > dbSize {
					_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 20)))
					return _sqlite3CorruptError(tls, int32(77337))
				}
			}
			rc = _relocatePage(tls, pBt, **(**uintptr)(__ccgo_up(bp + 20)), **(**Tu8)(__ccgo_up(bp)), **(**TPgno)(__ccgo_up(bp + 4)), **(**TPgno)(__ccgo_up(bp + 16)), bCommit)
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp + 20)))
			if rc != SQLITE_OK {
				return rc
			}
		}
	}
	if bCommit == 0 {
		for cond := true; cond; cond = iLastPg == libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize+libc.Uint32FromInt32(1) || _ptrmapPageno(tls, pBt, iLastPg) == iLastPg {
			iLastPg = iLastPg - 1
		}
		(*TBtShared)(unsafe.Pointer(pBt)).FbDoTruncate = uint8(1)
		(*TBtShared)(unsafe.Pointer(pBt)).FnPage = iLastPg
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Return True if it is possible that pIndex might be useful in
//	** implementing the ORDER BY clause in pBuilder.
//	**
//	** Return False if pBuilder does not contain an ORDER BY clause or
//	** if there is no way for pIndex to be useful in implementing that
//	** ORDER BY clause.
//	*/
func _indexMightHelpWithOrderBy(tls *libc.TLS, pBuilder uintptr, pIndex uintptr, iCursor int32) (r int32) {
	var aColExpr, pExpr, pOB, v1 uintptr
	var ii, jj int32
	_, _, _, _, _, _ = aColExpr, ii, jj, pExpr, pOB, v1
	if int32(uint32(*(*uint16)(unsafe.Pointer(pIndex + 56))&0x4>>2)) != 0 {
		return 0
	}
	v1 = (*TWhereInfo)(unsafe.Pointer((*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWInfo)).FpOrderBy
	pOB = v1
	if v1 == uintptr(0) {
		return 0
	}
	ii = 0
	for {
		if !(ii < (*TExprList)(unsafe.Pointer(pOB)).FnExpr) {
			break
		}
		pExpr = _sqlite3ExprSkipCollateAndLikely(tls, (*(*TExprList_item)(unsafe.Pointer(pOB + 8 + uintptr(ii)*20))).FpExpr)
		if pExpr == uintptr(0) {
			goto _2
		}
		if (libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_COLUMN)) && (*TExpr)(unsafe.Pointer(pExpr)).FiTable == iCursor {
			if int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) < 0 {
				return int32(1)
			}
			jj = 0
			for {
				if !(jj < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnKeyCol)) {
					break
				}
				if int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) == int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIndex)).FaiColumn + uintptr(jj)*2))) {
					return int32(1)
				}
				goto _3
			_3:
				;
				jj = jj + 1
			}
		} else {
			v1 = (*TIndex)(unsafe.Pointer(pIndex)).FaColExpr
			aColExpr = v1
			if v1 != uintptr(0) {
				jj = 0
				for {
					if !(jj < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnKeyCol)) {
						break
					}
					if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIndex)).FaiColumn + uintptr(jj)*2))) != -int32(2) {
						goto _5
					}
					if _sqlite3ExprCompareSkip(tls, pExpr, (*(*TExprList_item)(unsafe.Pointer(aColExpr + 8 + uintptr(jj)*20))).FpExpr, iCursor) == 0 {
						return int32(1)
					}
					goto _5
				_5:
					;
					jj = jj + 1
				}
			}
		}
		goto _2
	_2:
		;
		ii = ii + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** Populate the pIdx->aAvgEq[] array based on the samples currently
//	** stored in pIdx->aSample[].
//	*/
func _initAvgEq(tls *libc.TLS, pIdx uintptr) {
	var aSample, pFinal uintptr
	var avgEq, nRow, sumEq TtRowcnt
	var i, iCol, nCol, nSample int32
	var nDist100, nSum100 Ti64
	_, _, _, _, _, _, _, _, _, _, _ = aSample, avgEq, i, iCol, nCol, nDist100, nRow, nSample, nSum100, pFinal, sumEq
	if pIdx != 0 {
		aSample = (*TIndex)(unsafe.Pointer(pIdx)).FaSample
		pFinal = aSample + uintptr((*TIndex)(unsafe.Pointer(pIdx)).FnSample-int32(1))*20
		nCol = int32(1)
		if (*TIndex)(unsafe.Pointer(pIdx)).FnSampleCol > int32(1) {
			/* If this is stat4 data, then calculate aAvgEq[] values for all
			 ** sample columns except the last. The last is always set to 1, as
			 ** once the trailing PK fields are considered all index keys are
			 ** unique.  */
			nCol = (*TIndex)(unsafe.Pointer(pIdx)).FnSampleCol - int32(1)
			**(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaAvgEq + uintptr(nCol)*8)) = uint64(1)
		}
		iCol = 0
		for {
			if !(iCol < nCol) {
				break
			}
			nSample = (*TIndex)(unsafe.Pointer(pIdx)).FnSample /* Used to iterate through samples */
			sumEq = uint64(0)                                  /* Sum of the nEq values */
			avgEq = uint64(0)                                  /* Number of rows in index */
			nSum100 = 0                                        /* Number of distinct values in index */
			if !((*TIndex)(unsafe.Pointer(pIdx)).FaiRowEst != 0) || iCol >= libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol) || **(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiRowEst + uintptr(iCol+int32(1))*8)) == uint64(0) {
				nRow = **(**TtRowcnt)(__ccgo_up((*TIndexSample)(unsafe.Pointer(pFinal)).FanLt + uintptr(iCol)*8))
				nDist100 = libc.Int64FromUint64(libc.Uint64FromInt64(libc.Int64FromInt32(100)) * **(**TtRowcnt)(__ccgo_up((*TIndexSample)(unsafe.Pointer(pFinal)).FanDLt + uintptr(iCol)*8)))
				nSample = nSample - 1
			} else {
				nRow = **(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiRowEst))
				nDist100 = libc.Int64FromUint64(libc.Uint64FromInt64(libc.Int64FromInt32(100)) * **(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiRowEst)) / **(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiRowEst + uintptr(iCol+int32(1))*8)))
			}
			(*TIndex)(unsafe.Pointer(pIdx)).FnRowEst0 = nRow
			/* Set nSum to the number of distinct (iCol+1) field prefixes that
			 ** occur in the stat4 table for this index. Set sumEq to the sum of
			 ** the nEq values for column iCol for the same set (adding the value
			 ** only once where there exist duplicate prefixes).  */
			i = 0
			for {
				if !(i < nSample) {
					break
				}
				if i == (*TIndex)(unsafe.Pointer(pIdx)).FnSample-int32(1) || **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i)*20))).FanDLt + uintptr(iCol)*8)) != **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i+int32(1))*20))).FanDLt + uintptr(iCol)*8)) {
					sumEq = sumEq + **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i)*20))).FanEq + uintptr(iCol)*8))
					nSum100 = nSum100 + int64(100)
				}
				goto _2
			_2:
				;
				i = i + 1
			}
			if nDist100 > nSum100 && sumEq < nRow {
				avgEq = libc.Uint64FromInt64(libc.Int64FromInt32(100)) * (nRow - sumEq) / libc.Uint64FromInt64(nDist100-nSum100)
			}
			if avgEq == uint64(0) {
				avgEq = uint64(1)
			}
			**(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaAvgEq + uintptr(iCol)*8)) = avgEq
			goto _1
		_1:
			;
			iCol = iCol + 1
		}
	}
}

// C documentation
//
//	/*
//	** Insert a new cell on pPage at cell index "i".  pCell points to the
//	** content of the cell.
//	**
//	** If the cell content will fit on the page, then put it there.  If it
//	** will not fit, then make a copy of the cell content into pTemp if
//	** pTemp is not null.  Regardless of pTemp, allocate a new entry
//	** in pPage->apOvfl[] and make it point to the cell content (either
//	** in pTemp or the original pCell) and also record its index.
//	** Allocating a new entry in pPage->aCell[] implies that
//	** pPage->nOverflow is incremented.
//	**
//	** The insertCellFast() routine below works exactly the same as
//	** insertCell() except that it lacks the pTemp and iChild parameters
//	** which are assumed zero.  Other than that, the two routines are the
//	** same.
//	**
//	** Fixes or enhancements to this routine should be reflected in
//	** insertCellFast()!
//	*/
func _insertCell(tls *libc.TLS, pPage uintptr, i int32, pCell uintptr, sz int32, pTemp uintptr, iChild TPgno) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var data, pIns, v2 uintptr
	var j, rc int32
	var v1 Tu8
	var _ /* idx at bp+0 */ int32
	var _ /* rc2 at bp+4 */ int32
	_, _, _, _, _, _ = data, j, pIns, rc, v1, v2
	**(**int32)(__ccgo_up(bp)) = 0 /* The point in pPage->aCellIdx[] where no cell inserted */
	if (*TMemPage)(unsafe.Pointer(pPage)).FnOverflow != 0 || sz+int32(2) > (*TMemPage)(unsafe.Pointer(pPage)).FnFree {
		if pTemp != 0 {
			libc.Xmemcpy(tls, pTemp, pCell, libc.Uint32FromInt32(sz))
			pCell = pTemp
		}
		_sqlite3Put4byte(tls, pCell, iChild)
		v2 = pPage + 12
		v1 = *(*Tu8)(unsafe.Pointer(v2))
		*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) + 1
		j = libc.Int32FromUint8(v1)
		/* Comparison against ArraySize-1 since we hold back one extra slot
		 ** as a contingency.  In other words, never need more than 3 overflow
		 ** slots but 4 are allocated, just to be safe. */
		**(**uintptr)(__ccgo_up(pPage + 36 + uintptr(j)*4)) = pCell
		**(**Tu16)(__ccgo_up(pPage + 28 + uintptr(j)*2)) = libc.Uint16FromInt32(i)
		/* When multiple overflows occur, they are always sequential and in
		 ** sorted order.  This invariants arise because multiple overflows can
		 ** only occur when inserting divider cells into the parent page during
		 ** balancing, and the dividers are adjacent and sorted.
		 */
		/* Overflows in sorted order */
		/* Overflows are sequential */
	} else {
		rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
		if rc != SQLITE_OK {
			return rc
		}
		data = (*TMemPage)(unsafe.Pointer(pPage)).FaData
		rc = _allocateSpace(tls, pPage, sz, bp)
		if rc != 0 {
			return rc
		}
		/* The allocateSpace() routine guarantees the following properties
		 ** if it returns successfully */
		**(**int32)(__ccgo_up(pPage + 20)) -= libc.Int32FromUint16(libc.Uint16FromInt32(libc.Int32FromInt32(2) + sz))
		/* In a corrupt database where an entry in the cell index section of
		 ** a btree page has a value of 3 or less, the pCell value might point
		 ** as many as 4 bytes in front of the start of the aData buffer for
		 ** the source page.  Make sure this does not cause problems by not
		 ** reading the first 4 bytes */
		libc.Xmemcpy(tls, data+uintptr(**(**int32)(__ccgo_up(bp))+int32(4)), pCell+uintptr(4), libc.Uint32FromInt32(sz-int32(4)))
		_sqlite3Put4byte(tls, data+uintptr(**(**int32)(__ccgo_up(bp))), iChild)
		pIns = (*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(i*int32(2))
		libc.Xmemmove(tls, pIns+uintptr(2), pIns, libc.Uint32FromInt32(int32(2)*(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)-i)))
		**(**Tu8)(__ccgo_up(pIns)) = libc.Uint8FromInt32(**(**int32)(__ccgo_up(bp)) >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(pIns + 1)) = libc.Uint8FromInt32(**(**int32)(__ccgo_up(bp)))
		(*TMemPage)(unsafe.Pointer(pPage)).FnCell = (*TMemPage)(unsafe.Pointer(pPage)).FnCell + 1
		/* increment the cell count */
		v2 = data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(4))
		*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) + 1
		v1 = *(*Tu8)(unsafe.Pointer(v2))
		if libc.Int32FromUint8(v1) == 0 {
			**(**Tu8)(__ccgo_up(data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(3)))) = **(**Tu8)(__ccgo_up(data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(3)))) + 1
		}
		if (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FautoVacuum != 0 {
			**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
			/* The cell may contain a pointer to an overflow page. If so, write
			 ** the entry for the overflow page into the pointer map.
			 */
			_ptrmapPutOvflPtr(tls, pPage, pPage, pCell, bp+4)
			if **(**int32)(__ccgo_up(bp + 4)) != 0 {
				return **(**int32)(__ccgo_up(bp + 4))
			}
		}
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This variant of insertCell() assumes that the pTemp and iChild
//	** parameters are both zero.  Use this variant in sqlite3BtreeInsert()
//	** for performance improvement, and also so that this variant is only
//	** called from that one place, and is thus inlined, and thus runs must
//	** faster.
//	**
//	** Fixes or enhancements to this routine should be reflected into
//	** the insertCell() routine.
//	*/
func _insertCellFast(tls *libc.TLS, pPage uintptr, i int32, pCell uintptr, sz int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var data, pIns, v2 uintptr
	var j, rc int32
	var v1 Tu8
	var _ /* idx at bp+0 */ int32
	var _ /* rc2 at bp+4 */ int32
	_, _, _, _, _, _ = data, j, pIns, rc, v1, v2
	**(**int32)(__ccgo_up(bp)) = 0 /* The point in pPage->aCellIdx[] where no cell inserted */
	if sz+int32(2) > (*TMemPage)(unsafe.Pointer(pPage)).FnFree {
		v2 = pPage + 12
		v1 = *(*Tu8)(unsafe.Pointer(v2))
		*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) + 1
		j = libc.Int32FromUint8(v1)
		/* Comparison against ArraySize-1 since we hold back one extra slot
		 ** as a contingency.  In other words, never need more than 3 overflow
		 ** slots but 4 are allocated, just to be safe. */
		**(**uintptr)(__ccgo_up(pPage + 36 + uintptr(j)*4)) = pCell
		**(**Tu16)(__ccgo_up(pPage + 28 + uintptr(j)*2)) = libc.Uint16FromInt32(i)
		/* When multiple overflows occur, they are always sequential and in
		 ** sorted order.  This invariants arise because multiple overflows can
		 ** only occur when inserting divider cells into the parent page during
		 ** balancing, and the dividers are adjacent and sorted.
		 */
		/* Overflows in sorted order */
		/* Overflows are sequential */
	} else {
		rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
		if rc != SQLITE_OK {
			return rc
		}
		data = (*TMemPage)(unsafe.Pointer(pPage)).FaData
		rc = _allocateSpace(tls, pPage, sz, bp)
		if rc != 0 {
			return rc
		}
		/* The allocateSpace() routine guarantees the following properties
		 ** if it returns successfully */
		**(**int32)(__ccgo_up(pPage + 20)) -= libc.Int32FromUint16(libc.Uint16FromInt32(libc.Int32FromInt32(2) + sz))
		libc.Xmemcpy(tls, data+uintptr(**(**int32)(__ccgo_up(bp))), pCell, libc.Uint32FromInt32(sz))
		pIns = (*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(i*int32(2))
		libc.Xmemmove(tls, pIns+uintptr(2), pIns, libc.Uint32FromInt32(int32(2)*(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell)-i)))
		**(**Tu8)(__ccgo_up(pIns)) = libc.Uint8FromInt32(**(**int32)(__ccgo_up(bp)) >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(pIns + 1)) = libc.Uint8FromInt32(**(**int32)(__ccgo_up(bp)))
		(*TMemPage)(unsafe.Pointer(pPage)).FnCell = (*TMemPage)(unsafe.Pointer(pPage)).FnCell + 1
		/* increment the cell count */
		v2 = data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(4))
		*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) + 1
		v1 = *(*Tu8)(unsafe.Pointer(v2))
		if libc.Int32FromUint8(v1) == 0 {
			**(**Tu8)(__ccgo_up(data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(3)))) = **(**Tu8)(__ccgo_up(data + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(3)))) + 1
		}
		if (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPage)).FpBt)).FautoVacuum != 0 {
			**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
			/* The cell may contain a pointer to an overflow page. If so, write
			 ** the entry for the overflow page into the pointer map.
			 */
			_ptrmapPutOvflPtr(tls, pPage, pPage, pCell, bp+4)
			if **(**int32)(__ccgo_up(bp + 4)) != 0 {
				return **(**int32)(__ccgo_up(bp + 4))
			}
		}
	}
	return SQLITE_OK
}

/*
** The following parameters determine how many adjacent pages get involved
** in a balancing operation.  NN is the number of neighbors on either side
** of the page that participate in the balancing operation.  NB is the
** total number of pages that participate, including the target page and
** NN neighbors on either side.
**
** The minimum value of NN is 1 (of course).  Increasing NN above 1
** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
** in exchange for a larger degradation in INSERT and UPDATE performance.
** The value of NN appears to give the best results overall.
**
** (Later:) The description above makes it seem as if these values are
** tunable - as if you could change them and recompile and it would all work.
** But that is unlikely.  NB has been 3 since the inception of SQLite and
** we have never tested any other value.
 */

// C documentation
//
//	/*
//	** Implementation of the instr() function.
//	**
//	** instr(haystack,needle) finds the first occurrence of needle
//	** in haystack and returns the number of previous characters plus 1,
//	** or 0 if needle does not occur within haystack.
//	**
//	** If both haystack and needle are BLOBs, then the result is one more than
//	** the number of bytes in haystack prior to the first occurrence of needle,
//	** or 0 if needle never occurs in haystack.
//	*/
func _instrFunc(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	var N, isText, nHaystack, nNeedle, typeHaystack, typeNeedle int32
	var firstChar uint8
	var pC1, pC2, zHaystack, zNeedle uintptr
	_, _, _, _, _, _, _, _, _, _, _ = N, firstChar, isText, nHaystack, nNeedle, pC1, pC2, typeHaystack, typeNeedle, zHaystack, zNeedle
	N = int32(1)
	pC1 = uintptr(0)
	pC2 = uintptr(0)
	_ = argc
	typeHaystack = Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(argv)))
	typeNeedle = Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
	if typeHaystack == int32(SQLITE_NULL) || typeNeedle == int32(SQLITE_NULL) {
		return
	}
	nHaystack = Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(argv)))
	nNeedle = Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
	if nNeedle > 0 {
		if typeHaystack == int32(SQLITE_BLOB) && typeNeedle == int32(SQLITE_BLOB) {
			zHaystack = Xsqlite3_value_blob(tls, **(**uintptr)(__ccgo_up(argv)))
			zNeedle = Xsqlite3_value_blob(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
			isText = 0
		} else {
			if typeHaystack != int32(SQLITE_BLOB) && typeNeedle != int32(SQLITE_BLOB) {
				zHaystack = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
				zNeedle = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
				isText = int32(1)
			} else {
				pC1 = Xsqlite3_value_dup(tls, **(**uintptr)(__ccgo_up(argv)))
				zHaystack = Xsqlite3_value_text(tls, pC1)
				if zHaystack == uintptr(0) {
					goto endInstrOOM
				}
				nHaystack = Xsqlite3_value_bytes(tls, pC1)
				pC2 = Xsqlite3_value_dup(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
				zNeedle = Xsqlite3_value_text(tls, pC2)
				if zNeedle == uintptr(0) {
					goto endInstrOOM
				}
				nNeedle = Xsqlite3_value_bytes(tls, pC2)
				isText = int32(1)
			}
		}
		if zNeedle == uintptr(0) || nHaystack != 0 && zHaystack == uintptr(0) {
			goto endInstrOOM
		}
		firstChar = **(**uint8)(__ccgo_up(zNeedle))
		for nNeedle <= nHaystack && (libc.Int32FromUint8(**(**uint8)(__ccgo_up(zHaystack))) != libc.Int32FromUint8(firstChar) || libc.Xmemcmp(tls, zHaystack, zNeedle, libc.Uint32FromInt32(nNeedle)) != 0) {
			N = N + 1
			for cond := true; cond; cond = isText != 0 && libc.Int32FromUint8(**(**uint8)(__ccgo_up(zHaystack)))&int32(0xc0) == int32(0x80) {
				nHaystack = nHaystack - 1
				zHaystack = zHaystack + 1
			}
		}
		if nNeedle > nHaystack {
			N = 0
		}
	}
	Xsqlite3_result_int(tls, context, N)
	goto endInstr
endInstr:
	;
	Xsqlite3_value_free(tls, pC1)
	Xsqlite3_value_free(tls, pC2)
	return
	goto endInstrOOM
endInstrOOM:
	;
	Xsqlite3_result_error_nomem(tls, context)
	goto endInstr
}

// C documentation
//
//	/*
//	** Check to see if the pExpr expression is a form that needs to be passed
//	** to the xBestIndex method of virtual tables.  Forms of interest include:
//	**
//	**          Expression                   Virtual Table Operator
//	**          -----------------------      ---------------------------------
//	**      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
//	**      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
//	**      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
//	**      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
//	**      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
//	**      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
//	**      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
//	**      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
//	**      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
//	**
//	** In every case, "column" must be a column of a virtual table.  If there
//	** is a match, set *ppLeft to the "column" expression, set *ppRight to the
//	** "expr" expression (even though in forms (6) and (8) the column is on the
//	** right and the expression is on the left).  Also set *peOp2 to the
//	** appropriate virtual table operator.  The return value is 1 or 2 if there
//	** is a match.  The usual return is 1, but if the RHS is also a column
//	** of virtual table in forms (5) or (7) then return 2.
//	**
//	** If the expression matches none of the patterns above, return 0.
//	*/
func _isAuxiliaryVtabOperator(tls *libc.TLS, db uintptr, pExpr uintptr, peOp2 uintptr, ppLeft uintptr, ppRight uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, res, v1 int32
	var pCol, pLeft, pList, pMod, pRight, pVtab, t uintptr
	var v2 bool
	var _ /* pNotUsed at bp+4 */ uintptr
	var _ /* xNotUsed at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _ = i, pCol, pLeft, pList, pMod, pRight, pVtab, res, t, v1, v2
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_FUNCTION) {
		pList = *(*uintptr)(unsafe.Pointer(pExpr + 20))
		if pList == uintptr(0) || (*TExprList)(unsafe.Pointer(pList)).FnExpr != int32(2) {
			return 0
		}
		/* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
		 ** virtual table on their second argument, which is the same as
		 ** the left-hand side operand in their in-fix form.
		 **
		 **       vtab_column MATCH expression
		 **       MATCH(expression,vtab_column)
		 */
		pCol = (*(*TExprList_item)(unsafe.Pointer(pList + 8 + 1*20))).FpExpr
		if v2 = libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pCol)).Fop) == int32(TK_COLUMN) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pCol)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB); v2 {
			v1 = _sqlite3ExprIsLikeOperator(tls, pExpr)
			i = v1
		}
		if v2 && v1 != 0 {
			**(**uint8)(__ccgo_up(peOp2)) = libc.Uint8FromInt32(i)
			**(**uintptr)(__ccgo_up(ppRight)) = (*(*TExprList_item)(unsafe.Pointer(pList + 8))).FpExpr
			**(**uintptr)(__ccgo_up(ppLeft)) = pCol
			return int32(1)
		}
		/* We can also match against the first column of overloaded
		 ** functions where xFindFunction returns a value of at least
		 ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
		 **
		 **      OVERLOADED(vtab_column,expression)
		 **
		 ** Historically, xFindFunction expected to see lower-case function
		 ** names.  But for this use case, xFindFunction is expected to deal
		 ** with function names in an arbitrary case.
		 */
		pCol = (*(*TExprList_item)(unsafe.Pointer(pList + 8))).FpExpr
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pCol)).Fop) == int32(TK_COLUMN) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pCol)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB) {
			pVtab = (*TVTable)(unsafe.Pointer(_sqlite3GetVTable(tls, db, (*TExpr)(unsafe.Pointer(pCol)).Fy.FpTab))).FpVtab
			pMod = (*Tsqlite3_vtab)(unsafe.Pointer(pVtab)).FpModule
			if (*Tsqlite3_module)(unsafe.Pointer(pMod)).FxFindFunction != uintptr(0) {
				i = (*(*func(*libc.TLS, uintptr, int32, uintptr, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_module)(unsafe.Pointer(pMod)).FxFindFunction})))(tls, pVtab, int32(2), *(*uintptr)(unsafe.Pointer(pExpr + 8)), bp, bp+4)
				if i >= int32(SQLITE_INDEX_CONSTRAINT_FUNCTION) {
					**(**uint8)(__ccgo_up(peOp2)) = libc.Uint8FromInt32(i)
					**(**uintptr)(__ccgo_up(ppRight)) = (*(*TExprList_item)(unsafe.Pointer(pList + 8 + 1*20))).FpExpr
					**(**uintptr)(__ccgo_up(ppLeft)) = pCol
					return int32(1)
				}
			}
		}
	} else {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) >= int32(TK_EQ) {
			/* Comparison operators are a common case.  Save a few comparisons for
			 ** that common case by terminating early. */
			return 0
		} else {
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_NE) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_ISNOT) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_NOTNULL) {
				res = 0
				pLeft = (*TExpr)(unsafe.Pointer(pExpr)).FpLeft
				pRight = (*TExpr)(unsafe.Pointer(pExpr)).FpRight
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pLeft)).Fop) == int32(TK_COLUMN) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pLeft)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB) {
					res = res + 1
				}
				if pRight != 0 && (libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pRight)).Fop) == int32(TK_COLUMN) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pRight)).Fy.FpTab)).FeTabType) == int32(TABTYP_VTAB)) {
					res = res + 1
					t = pLeft
					pLeft = pRight
					pRight = t
				}
				**(**uintptr)(__ccgo_up(ppLeft)) = pLeft
				**(**uintptr)(__ccgo_up(ppRight)) = pRight
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_NE) {
					**(**uint8)(__ccgo_up(peOp2)) = uint8(SQLITE_INDEX_CONSTRAINT_NE)
				}
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_ISNOT) {
					**(**uint8)(__ccgo_up(peOp2)) = uint8(SQLITE_INDEX_CONSTRAINT_ISNOT)
				}
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_NOTNULL) {
					**(**uint8)(__ccgo_up(peOp2)) = uint8(SQLITE_INDEX_CONSTRAINT_ISNOTNULL)
				}
				return res
			}
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** pX is the RHS of an IN operator.  If pX is a SELECT statement
//	** that can be simplified to a direct table access, then return
//	** a pointer to the SELECT statement.  If pX is not a SELECT statement,
//	** or if the SELECT statement needs to be materialized into a transient
//	** table, then return NULL.
//	*/
func _isCandidateForInOpt(tls *libc.TLS, pX uintptr) (r uintptr) {
	var i int32
	var p, pEList, pRes, pSrc, pTab uintptr
	_, _, _, _, _, _ = i, p, pEList, pRes, pSrc, pTab
	if !((*TExpr)(unsafe.Pointer(pX)).Fflags&libc.Uint32FromInt32(EP_xIsSelect) != libc.Uint32FromInt32(0)) {
		return uintptr(0)
	} /* Not a subquery */
	if (*TExpr)(unsafe.Pointer(pX)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_VarSelect)) != uint32(0) {
		return uintptr(0)
	} /* Correlated subq */
	p = *(*uintptr)(unsafe.Pointer(pX + 20))
	if (*TSelect)(unsafe.Pointer(p)).FpPrior != 0 {
		return uintptr(0)
	} /* Not a compound SELECT */
	if (*TSelect)(unsafe.Pointer(p)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Distinct)|libc.Int32FromInt32(SF_Aggregate)) != 0 {
		return uintptr(0) /* No DISTINCT keyword and no aggregate functions */
	}
	/* Has no GROUP BY clause */
	if (*TSelect)(unsafe.Pointer(p)).FpLimit != 0 {
		return uintptr(0)
	} /* Has no LIMIT clause */
	if (*TSelect)(unsafe.Pointer(p)).FpWhere != 0 {
		return uintptr(0)
	} /* Has no WHERE clause */
	pSrc = (*TSelect)(unsafe.Pointer(p)).FpSrc
	if (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc != int32(1) {
		return uintptr(0)
	} /* Single term in FROM clause */
	if int32(*(*uint32)(unsafe.Pointer(pSrc + 8 + 12 + 4))&0x4>>2) != 0 {
		return uintptr(0)
	} /* FROM is not a subquery or view */
	pTab = (*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FpSTab
	/* FROM clause is not a view */
	if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VTAB) {
		return uintptr(0)
	} /* FROM clause not a virtual table */
	pEList = (*TSelect)(unsafe.Pointer(p)).FpEList
	/* All SELECT results must be columns. */
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pEList)).FnExpr) {
			break
		}
		pRes = (*(*TExprList_item)(unsafe.Pointer(pEList + 8 + uintptr(i)*20))).FpExpr
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pRes)).Fop) != int32(TK_COLUMN) {
			return uintptr(0)
		}
		/* Not a correlated subquery */
		goto _1
	_1:
		;
		i = i + 1
	}
	return p
}

// C documentation
//
//	/*
//	** Return true if the DISTINCT expression-list passed as the third argument
//	** is redundant.
//	**
//	** A DISTINCT list is redundant if any subset of the columns in the
//	** DISTINCT list are collectively unique and individually non-null.
//	*/
func _isDistinctRedundant(tls *libc.TLS, pParse uintptr, pTabList uintptr, pWC uintptr, pDistinct uintptr) (r int32) {
	var i, iBase int32
	var p, pIdx, pTab uintptr
	_, _, _, _, _ = i, iBase, p, pIdx, pTab
	/* If there is more than one table or sub-select in the FROM clause of
	 ** this query, then it will not be possible to show that the DISTINCT
	 ** clause is redundant. */
	if (*TSrcList)(unsafe.Pointer(pTabList)).FnSrc != int32(1) {
		return 0
	}
	iBase = (*(*TSrcItem)(unsafe.Pointer(pTabList + 8))).FiCursor
	pTab = (*(*TSrcItem)(unsafe.Pointer(pTabList + 8))).FpSTab
	/* If any of the expressions is an IPK column on table iBase, then return
	 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
	 ** current SELECT is a correlated sub-query.
	 */
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pDistinct)).FnExpr) {
			break
		}
		p = _sqlite3ExprSkipCollateAndLikely(tls, (*(*TExprList_item)(unsafe.Pointer(pDistinct + 8 + uintptr(i)*20))).FpExpr)
		if p == uintptr(0) {
			goto _1
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) != int32(TK_COLUMN) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) != int32(TK_AGG_COLUMN) {
			goto _1
		}
		if (*TExpr)(unsafe.Pointer(p)).FiTable == iBase && int32((*TExpr)(unsafe.Pointer(p)).FiColumn) < 0 {
			return int32(1)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	/* Loop through all indices on the table, checking each to see if it makes
	 ** the DISTINCT qualifier redundant. It does so if:
	 **
	 **   1. The index is itself UNIQUE, and
	 **
	 **   2. All of the columns in the index are either part of the pDistinct
	 **      list, or else the WHERE clause contains a term of the form "col=X",
	 **      where X is a constant value. The collation sequences of the
	 **      comparison and select-list expressions must match those of the index.
	 **
	 **   3. All of those index columns for which the WHERE clause does not
	 **      contain a "col=X" term are subject to a NOT NULL constraint.
	 */
	pIdx = (*TTable)(unsafe.Pointer(pTab)).FpIndex
	for {
		if !(pIdx != 0) {
			break
		}
		if !(libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pIdx)).FonError) != libc.Int32FromInt32(OE_None)) {
			goto _2
		}
		if (*TIndex)(unsafe.Pointer(pIdx)).FpPartIdxWhere != 0 {
			goto _2
		}
		i = 0
		for {
			if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)) {
				break
			}
			if uintptr(0) == _sqlite3WhereFindTerm(tls, pWC, iBase, i, ^libc.Uint64FromInt32(0), uint32(WO_EQ), pIdx) {
				if _findIndexCol(tls, pParse, pDistinct, iBase, pIdx, i) < 0 {
					break
				}
				if _indexColumnNotNull(tls, pIdx, i) == 0 {
					break
				}
			}
			goto _3
		_3:
			;
			i = i + 1
		}
		if i == libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol) {
			/* This index implies that the DISTINCT qualifier is redundant. */
			return int32(1)
		}
		goto _2
	_2:
		;
		pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
	}
	return 0
}

// C documentation
//
//	/*
//	** Return true if the parser passed as the first argument is being
//	** used to code a trigger that is really a "SET NULL" action belonging
//	** to trigger pFKey.
//	*/
func _isSetNullAction(tls *libc.TLS, pParse uintptr, pFKey uintptr) (r int32) {
	var p, pTop, v1 uintptr
	_, _, _ = p, pTop, v1
	if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
		v1 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
	} else {
		v1 = pParse
	}
	pTop = v1
	if (*TParse)(unsafe.Pointer(pTop)).FpTriggerPrg != 0 {
		p = (*TTriggerPrg)(unsafe.Pointer((*TParse)(unsafe.Pointer(pTop)).FpTriggerPrg)).FpTrigger
		if p == **(**uintptr)(__ccgo_up(pFKey + 28)) && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pFKey + 25))) == int32(OE_SetNull) || p == **(**uintptr)(__ccgo_up(pFKey + 28 + 1*4)) && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pFKey + 25 + 1))) == int32(OE_SetNull) {
			return int32(1)
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** The select statement passed as the first argument is an aggregate query.
//	** The second argument is the associated aggregate-info object. This
//	** function tests if the SELECT is of the form:
//	**
//	**   SELECT count(*) FROM <tbl>
//	**
//	** where table is a database table, not a sub-select or view. If the query
//	** does match this pattern, then a pointer to the Table object representing
//	** <tbl> is returned. Otherwise, NULL is returned.
//	**
//	** This routine checks to see if it is safe to use the count optimization.
//	** A correct answer is still obtained (though perhaps more slowly) if
//	** this routine returns NULL when it could have returned a table pointer.
//	** But returning the pointer when NULL should have been returned can
//	** result in incorrect answers and/or crashes.  So, when in doubt, return NULL.
//	*/
func _isSimpleCount(tls *libc.TLS, p uintptr, pAggInfo uintptr) (r uintptr) {
	var pExpr, pTab uintptr
	_, _ = pExpr, pTab
	if (*TSelect)(unsafe.Pointer(p)).FpWhere != 0 || (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpEList)).FnExpr != int32(1) || (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc)).FnSrc != int32(1) || int32(*(*uint32)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8 + 12 + 4))&0x4>>2) != 0 || (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnFunc != int32(1) || (*TSelect)(unsafe.Pointer(p)).FpHaving != 0 {
		return uintptr(0)
	}
	pTab = (*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8))).FpSTab
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_NORM)) {
		return uintptr(0)
	}
	pExpr = (*(*TExprList_item)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpEList + 8))).FpExpr
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_AGG_FUNCTION) {
		return uintptr(0)
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo != pAggInfo {
		return uintptr(0)
	}
	if (*TFuncDef)(unsafe.Pointer((**(**TAggInfo_func)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc))).FpFunc)).FfuncFlags&uint32(SQLITE_FUNC_COUNT) == uint32(0) {
		return uintptr(0)
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Distinct)|libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
		return uintptr(0)
	}
	return pTab
}

// C documentation
//
//	/*
//	** Edit the payload size of the element at iRoot by the amount in
//	** pParse->delta.
//	*/
func _jsonAfterEditSizeAdjust(tls *libc.TLS, pParse uintptr, iRoot Tu32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nBlob Tu32
	var _ /* sz at bp+0 */ Tu32
	_ = nBlob
	**(**Tu32)(__ccgo_up(bp)) = uint32(0)
	nBlob = (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob
	(*TJsonParse)(unsafe.Pointer(pParse)).FnBlob = (*TJsonParse)(unsafe.Pointer(pParse)).FnBlobAlloc
	_jsonbPayloadSize(tls, pParse, iRoot, bp)
	(*TJsonParse)(unsafe.Pointer(pParse)).FnBlob = nBlob
	**(**Tu32)(__ccgo_up(bp)) = **(**Tu32)(__ccgo_up(bp)) + libc.Uint32FromInt32((*TJsonParse)(unsafe.Pointer(pParse)).Fdelta)
	**(**int32)(__ccgo_up(pParse + 40)) += _jsonBlobChangePayloadSize(tls, pParse, iRoot, **(**Tu32)(__ccgo_up(bp)))
}

// C documentation
//
//	/* Append a node type byte together with the payload size and
//	** possibly also the payload.
//	**
//	** If aPayload is not NULL, then it is a pointer to the payload which
//	** is also appended.  If aPayload is NULL, the pParse->aBlob[] array
//	** is resized (if necessary) so that it is big enough to hold the
//	** payload, but the payload is not appended and pParse->nBlob is left
//	** pointing to where the first byte of payload will eventually be.
//	*/
func _jsonBlobAppendNode(tls *libc.TLS, pParse uintptr, eType Tu8, szPayload Tu64, aPayload uintptr) {
	var a, v1 uintptr
	_, _ = a, v1
	if uint64((*TJsonParse)(unsafe.Pointer(pParse)).FnBlob)+szPayload+uint64(9) > uint64((*TJsonParse)(unsafe.Pointer(pParse)).FnBlobAlloc) {
		_jsonBlobExpandAndAppendNode(tls, pParse, eType, szPayload, aPayload)
		return
	}
	a = (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob + uintptr((*TJsonParse)(unsafe.Pointer(pParse)).FnBlob)
	if szPayload <= uint64(11) {
		**(**Tu8)(__ccgo_up(a)) = uint8(uint64(eType) | szPayload<<libc.Int32FromInt32(4))
		**(**Tu32)(__ccgo_up(pParse + 4)) += uint32(1)
	} else {
		if szPayload <= uint64(0xff) {
			**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(eType) | int32(0xc0))
			**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload & uint64(0xff))
			**(**Tu32)(__ccgo_up(pParse + 4)) += uint32(2)
		} else {
			if szPayload <= uint64(0xffff) {
				**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(eType) | int32(0xd0))
				**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload >> libc.Int32FromInt32(8) & uint64(0xff))
				**(**Tu8)(__ccgo_up(a + 2)) = uint8(szPayload & uint64(0xff))
				**(**Tu32)(__ccgo_up(pParse + 4)) += uint32(3)
			} else {
				**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(eType) | int32(0xe0))
				**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload >> libc.Int32FromInt32(24) & uint64(0xff))
				**(**Tu8)(__ccgo_up(a + 2)) = uint8(szPayload >> libc.Int32FromInt32(16) & uint64(0xff))
				**(**Tu8)(__ccgo_up(a + 3)) = uint8(szPayload >> libc.Int32FromInt32(8) & uint64(0xff))
				**(**Tu8)(__ccgo_up(a + 4)) = uint8(szPayload & uint64(0xff))
				**(**Tu32)(__ccgo_up(pParse + 4)) += uint32(5)
			}
		}
	}
	if aPayload != 0 {
		v1 = pParse + 4
		*(*Tu32)(unsafe.Pointer(v1)) = Tu32(uint64(*(*Tu32)(unsafe.Pointer(v1))) + szPayload)
		libc.Xmemcpy(tls, (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob+uintptr(uint64((*TJsonParse)(unsafe.Pointer(pParse)).FnBlob)-szPayload), aPayload, uint32(szPayload))
	}
}

// C documentation
//
//	/* Change the payload size for the node at index i to be szPayload.
//	*/
func _jsonBlobChangePayloadSize(tls *libc.TLS, pParse uintptr, i Tu32, szPayload Tu32) (r int32) {
	var a uintptr
	var delta int32
	var nExtra, nNeeded, szType Tu8
	var newSize Tu32
	_, _, _, _, _, _ = a, delta, nExtra, nNeeded, newSize, szType
	if (*TJsonParse)(unsafe.Pointer(pParse)).Foom != 0 {
		return 0
	}
	a = (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob + uintptr(i)
	szType = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a))) >> int32(4))
	if libc.Int32FromUint8(szType) <= int32(11) {
		nExtra = uint8(0)
	} else {
		if libc.Int32FromUint8(szType) == int32(12) {
			nExtra = uint8(1)
		} else {
			if libc.Int32FromUint8(szType) == int32(13) {
				nExtra = uint8(2)
			} else {
				if libc.Int32FromUint8(szType) == int32(14) {
					nExtra = uint8(4)
				} else {
					nExtra = uint8(8)
				}
			}
		}
	}
	if szPayload <= uint32(11) {
		nNeeded = uint8(0)
	} else {
		if szPayload <= uint32(0xff) {
			nNeeded = uint8(1)
		} else {
			if szPayload <= uint32(0xffff) {
				nNeeded = uint8(2)
			} else {
				nNeeded = uint8(4)
			}
		}
	}
	delta = libc.Int32FromUint8(nNeeded) - libc.Int32FromUint8(nExtra)
	if delta != 0 {
		newSize = (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob + libc.Uint32FromInt32(delta)
		if delta > 0 {
			if newSize > (*TJsonParse)(unsafe.Pointer(pParse)).FnBlobAlloc && _jsonBlobExpand(tls, pParse, newSize) != 0 {
				return 0 /* OOM error.  Error state recorded in pParse->oom. */
			}
			a = (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob + uintptr(i)
			libc.Xmemmove(tls, a+uintptr(int32(1)+delta), a+1, (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob-(i+uint32(1)))
		} else {
			libc.Xmemmove(tls, a+1, a+uintptr(int32(1)-delta), (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob-(i+uint32(1)-libc.Uint32FromInt32(delta)))
		}
		(*TJsonParse)(unsafe.Pointer(pParse)).FnBlob = newSize
	}
	if libc.Int32FromUint8(nNeeded) == 0 {
		**(**Tu8)(__ccgo_up(a)) = uint8(libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a)))&libc.Int32FromInt32(0x0f)) | szPayload<<libc.Int32FromInt32(4))
	} else {
		if libc.Int32FromUint8(nNeeded) == int32(1) {
			**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a)))&int32(0x0f) | int32(0xc0))
			**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload & uint32(0xff))
		} else {
			if libc.Int32FromUint8(nNeeded) == int32(2) {
				**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a)))&int32(0x0f) | int32(0xd0))
				**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload >> libc.Int32FromInt32(8) & uint32(0xff))
				**(**Tu8)(__ccgo_up(a + 2)) = uint8(szPayload & uint32(0xff))
			} else {
				**(**Tu8)(__ccgo_up(a)) = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a)))&int32(0x0f) | int32(0xe0))
				**(**Tu8)(__ccgo_up(a + 1)) = uint8(szPayload >> libc.Int32FromInt32(24) & uint32(0xff))
				**(**Tu8)(__ccgo_up(a + 2)) = uint8(szPayload >> libc.Int32FromInt32(16) & uint32(0xff))
				**(**Tu8)(__ccgo_up(a + 3)) = uint8(szPayload >> libc.Int32FromInt32(8) & uint32(0xff))
				**(**Tu8)(__ccgo_up(a + 4)) = uint8(szPayload & uint32(0xff))
			}
		}
	}
	return delta
}

// C documentation
//
//	/*
//	** Modify the JSONB blob at pParse->aBlob by removing nDel bytes of
//	** content beginning at iDel, and replacing them with nIns bytes of
//	** content given by aIns.
//	**
//	** nDel may be zero, in which case no bytes are removed.  But iDel is
//	** still important as new bytes will be insert beginning at iDel.
//	**
//	** aIns may be zero, in which case space is created to hold nIns bytes
//	** beginning at iDel, but that space is uninitialized.
//	**
//	** Set pParse->oom if an OOM occurs.
//	*/
func _jsonBlobEdit(tls *libc.TLS, pParse uintptr, iDel Tu32, nDel Tu32, aIns uintptr, nIns Tu32) {
	var d Ti64
	var v1 uintptr
	_, _ = d, v1
	d = libc.Int64FromUint32(nIns) - libc.Int64FromUint32(nDel)
	if d < 0 && d >= int64(-libc.Int32FromInt32(8)) && aIns != uintptr(0) && _jsonBlobOverwrite(tls, (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob+uintptr(iDel), aIns, nIns, libc.Uint32FromInt32(int32(-d))) != 0 {
		return
	}
	if d != 0 {
		if libc.Int64FromUint32((*TJsonParse)(unsafe.Pointer(pParse)).FnBlob)+d > libc.Int64FromUint32((*TJsonParse)(unsafe.Pointer(pParse)).FnBlobAlloc) {
			_jsonBlobExpand(tls, pParse, libc.Uint32FromInt64(libc.Int64FromUint32((*TJsonParse)(unsafe.Pointer(pParse)).FnBlob)+d))
			if (*TJsonParse)(unsafe.Pointer(pParse)).Foom != 0 {
				return
			}
		}
		libc.Xmemmove(tls, (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob+uintptr(iDel+nIns), (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob+uintptr(iDel+nDel), (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob-(iDel+nDel))
		v1 = pParse + 4
		*(*Tu32)(unsafe.Pointer(v1)) = Tu32(int64(*(*Tu32)(unsafe.Pointer(v1))) + d)
		v1 = pParse + 40
		*(*int32)(unsafe.Pointer(v1)) = int32(int64(*(*int32)(unsafe.Pointer(v1))) + d)
	}
	if nIns != 0 && aIns != 0 {
		libc.Xmemcpy(tls, (*TJsonParse)(unsafe.Pointer(pParse)).FaBlob+uintptr(iDel), aIns, nIns)
	}
}

// C documentation
//
//	/* Expand pParse->aBlob and append one bytes.
//	*/
func _jsonBlobExpandAndAppendOneByte(tls *libc.TLS, pParse uintptr, c Tu8) {
	var v1 Tu32
	var v2 uintptr
	_, _ = v1, v2
	_jsonBlobExpand(tls, pParse, (*TJsonParse)(unsafe.Pointer(pParse)).FnBlob+uint32(1))
	if libc.Int32FromUint8((*TJsonParse)(unsafe.Pointer(pParse)).Foom) == 0 {
		v2 = pParse + 4
		v1 = *(*Tu32)(unsafe.Pointer(v2))
		*(*Tu32)(unsafe.Pointer(v2)) = *(*Tu32)(unsafe.Pointer(v2)) + 1
		**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pParse)).FaBlob + uintptr(v1))) = c
	}
}

// C documentation
//
//	/*
//	** If the JSONB at aIns[0..nIns-1] can be expanded (by denormalizing the
//	** size field) by d bytes, then write the expansion into aOut[] and
//	** return true.  In this way, an overwrite happens without changing the
//	** size of the JSONB, which reduces memcpy() operations and also make it
//	** faster and easier to update the B-Tree entry that contains the JSONB
//	** in the database.
//	**
//	** If the expansion of aIns[] by d bytes cannot be (easily) accomplished
//	** then return false.
//	**
//	** The d parameter is guaranteed to be between 1 and 8.
//	**
//	** This routine is an optimization.  A correct answer is obtained if it
//	** always leaves the output unchanged and returns false.
//	*/
func _jsonBlobOverwrite(tls *libc.TLS, aOut uintptr, aIns uintptr, nIns Tu32, d Tu32) (r int32) {
	var i, szPayload Tu32
	var szHdr Tu8
	_, _, _ = i, szHdr, szPayload /* Size of header before expansion */
	if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aIns)))&int32(0x0f) <= int32(2) {
		return 0
	} /* Cannot enlarge NULL, true, false */
	switch libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aIns))) >> libc.Int32FromInt32(4) {
	default: /* aIns[] header size 1 */
		if int32(1)<<d&int32(0x116) == 0 {
			return 0
		} /* d must be 1, 2, 4, or 8 */
		i = d + uint32(1) /* New hdr sz: 2, 3, 5, or 9 */
		szHdr = uint8(1)
	case int32(12): /* aIns[] header size is 2 */
		if int32(1)<<d&int32(0x8a) == 0 {
			return 0
		} /* d must be 1, 3, or 7 */
		i = d + uint32(2) /* New hdr sz: 2, 5, or 9 */
		szHdr = uint8(2)
	case int32(13): /* aIns[] header size is 3 */
		if d != uint32(2) && d != uint32(6) {
			return 0
		} /* d must be 2 or 6 */
		i = d + uint32(3) /* New hdr sz: 5 or 9 */
		szHdr = uint8(3)
	case int32(14): /* aIns[] header size is 5 */
		if d != uint32(4) {
			return 0
		} /* d must be 4 */
		i = uint32(9) /* New hdr sz: 9 */
		szHdr = uint8(5)
	case int32(15): /* aIns[] header size is 9 */
		return 0 /* No solution */
	}
	**(**Tu8)(__ccgo_up(aOut)) = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aIns)))&int32(0x0f) | libc.Int32FromUint8(_aType1[i-uint32(2)]))
	libc.Xmemcpy(tls, aOut+uintptr(i), aIns+uintptr(szHdr), nIns-uint32(szHdr))
	szPayload = nIns - uint32(szHdr)
	for int32(1) != 0 {
		i = i - 1
		**(**Tu8)(__ccgo_up(aOut + uintptr(i))) = uint8(szPayload & uint32(0xff))
		if i == uint32(1) {
			break
		}
		szPayload = szPayload >> uint32(8)
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** Insert a new entry into the cache.  If the cache is full, expel
//	** the least recently used entry.  Return SQLITE_OK on success or a
//	** result code otherwise.
//	**
//	** Cache entries are stored in age order, oldest first.
//	*/
func _jsonCacheInsert(tls *libc.TLS, ctx uintptr, pParse uintptr) (r int32) {
	var db, p uintptr
	_, _ = db, p
	p = Xsqlite3_get_auxdata(tls, ctx, -int32(429938))
	if p == uintptr(0) {
		db = Xsqlite3_context_db_handle(tls, ctx)
		p = _sqlite3DbMallocZero(tls, db, uint64(24))
		if p == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		(*TJsonCache)(unsafe.Pointer(p)).Fdb = db
		Xsqlite3_set_auxdata(tls, ctx, -int32(429938), p, __ccgo_fp(_jsonCacheDeleteGeneric))
		p = Xsqlite3_get_auxdata(tls, ctx, -int32(429938))
		if p == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
	}
	if (*TJsonCache)(unsafe.Pointer(p)).FnUsed >= int32(JSON_CACHE_SIZE) {
		_jsonParseFree(tls, **(**uintptr)(__ccgo_up(p + 8)))
		libc.Xmemmove(tls, p+8, p+8+1*4, libc.Uint32FromInt32(libc.Int32FromInt32(JSON_CACHE_SIZE)-libc.Int32FromInt32(1))*libc.Uint32FromInt64(4))
		(*TJsonCache)(unsafe.Pointer(p)).FnUsed = libc.Int32FromInt32(JSON_CACHE_SIZE) - libc.Int32FromInt32(1)
	}
	(*TJsonParse)(unsafe.Pointer(pParse)).FeEdit = uint8(0)
	(*TJsonParse)(unsafe.Pointer(pParse)).FnJPRef = (*TJsonParse)(unsafe.Pointer(pParse)).FnJPRef + 1
	(*TJsonParse)(unsafe.Pointer(pParse)).FbReadOnly = uint8(1)
	**(**uintptr)(__ccgo_up(p + 8 + uintptr((*TJsonCache)(unsafe.Pointer(p)).FnUsed)*4)) = pParse
	(*TJsonCache)(unsafe.Pointer(p)).FnUsed = (*TJsonCache)(unsafe.Pointer(p)).FnUsed + 1
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Search for a cached translation the json text supplied by pArg.  Return
//	** the JsonParse object if found.  Return NULL if not found.
//	**
//	** When a match if found, the matching entry is moved to become the
//	** most-recently used entry if it isn't so already.
//	**
//	** The JsonParse object returned still belongs to the Cache and might
//	** be deleted at any moment.  If the caller wants the JsonParse to
//	** linger, it needs to increment the nPJRef reference counter.
//	*/
func _jsonCacheSearch(tls *libc.TLS, ctx uintptr, pArg uintptr) (r uintptr) {
	var i, nJson int32
	var p, tmp, zJson uintptr
	_, _, _, _, _ = i, nJson, p, tmp, zJson
	if Xsqlite3_value_type(tls, pArg) != int32(SQLITE_TEXT) {
		return uintptr(0)
	}
	zJson = Xsqlite3_value_text(tls, pArg)
	if zJson == uintptr(0) {
		return uintptr(0)
	}
	nJson = Xsqlite3_value_bytes(tls, pArg)
	p = Xsqlite3_get_auxdata(tls, ctx, -int32(429938))
	if p == uintptr(0) {
		return uintptr(0)
	}
	i = 0
	for {
		if !(i < (*TJsonCache)(unsafe.Pointer(p)).FnUsed) {
			break
		}
		if (*TJsonParse)(unsafe.Pointer(**(**uintptr)(__ccgo_up(p + 8 + uintptr(i)*4)))).FzJson == zJson {
			break
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	if i >= (*TJsonCache)(unsafe.Pointer(p)).FnUsed {
		i = 0
		for {
			if !(i < (*TJsonCache)(unsafe.Pointer(p)).FnUsed) {
				break
			}
			if (*TJsonParse)(unsafe.Pointer(**(**uintptr)(__ccgo_up(p + 8 + uintptr(i)*4)))).FnJson != nJson {
				goto _2
			}
			if libc.Xmemcmp(tls, (*TJsonParse)(unsafe.Pointer(**(**uintptr)(__ccgo_up(p + 8 + uintptr(i)*4)))).FzJson, zJson, libc.Uint32FromInt32(nJson)) == 0 {
				break
			}
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	if i < (*TJsonCache)(unsafe.Pointer(p)).FnUsed {
		if i < (*TJsonCache)(unsafe.Pointer(p)).FnUsed-int32(1) {
			/* Make the matching entry the most recently used entry */
			tmp = **(**uintptr)(__ccgo_up(p + 8 + uintptr(i)*4))
			libc.Xmemmove(tls, p+8+uintptr(i)*4, p+8+uintptr(i+int32(1))*4, libc.Uint32FromInt32((*TJsonCache)(unsafe.Pointer(p)).FnUsed-i-libc.Int32FromInt32(1))*uint32(4))
			**(**uintptr)(__ccgo_up(p + 8 + uintptr((*TJsonCache)(unsafe.Pointer(p)).FnUsed-int32(1))*4)) = tmp
			i = (*TJsonCache)(unsafe.Pointer(p)).FnUsed - int32(1)
		}
		return **(**uintptr)(__ccgo_up(p + 8 + uintptr(i)*4))
	} else {
		return uintptr(0)
	}
	return r
}

/**************************************************************************
** Utility routines for dealing with JsonString objects
**************************************************************************/

// C documentation
//
//	/* Advance the cursor to the next element for json_tree() */
func _jsonEachNext(tls *libc.TLS, cur uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, i1, iVal, n, n1 Tu32
	var levelChange, x Tu8
	var nNew Tu64
	var p, pNew, pParent, pParent1 uintptr
	var rc int32
	var _ /* sz at bp+0 */ Tu32
	var _ /* sz at bp+4 */ Tu32
	_, _, _, _, _, _, _, _, _, _, _, _, _ = i, i1, iVal, levelChange, n, n1, nNew, p, pNew, pParent, pParent1, rc, x
	p = cur
	rc = SQLITE_OK
	if (*TJsonEachCursor)(unsafe.Pointer(p)).FbRecursive != 0 {
		levelChange = uint8(0)
		**(**Tu32)(__ccgo_up(bp)) = uint32(0)
		i = libc.Uint32FromInt32(_jsonSkipLabel(tls, p))
		x = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FsParse.FaBlob + uintptr(i)))) & int32(0x0f))
		n = _jsonbPayloadSize(tls, p+168, i, bp)
		if libc.Int32FromUint8(x) == int32(JSONB_OBJECT) || libc.Int32FromUint8(x) == int32(JSONB_ARRAY) {
			if (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent >= (*TJsonEachCursor)(unsafe.Pointer(p)).FnParentAlloc {
				nNew = uint64((*TJsonEachCursor)(unsafe.Pointer(p)).FnParentAlloc*uint32(2) + uint32(3))
				pNew = _sqlite3DbRealloc(tls, (*TJsonEachCursor)(unsafe.Pointer(p)).Fdb, (*TJsonEachCursor)(unsafe.Pointer(p)).FaParent, uint64(24)*nNew)
				if pNew == uintptr(0) {
					return int32(SQLITE_NOMEM)
				}
				(*TJsonEachCursor)(unsafe.Pointer(p)).FnParentAlloc = uint32(nNew)
				(*TJsonEachCursor)(unsafe.Pointer(p)).FaParent = pNew
			}
			levelChange = uint8(1)
			pParent = (*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent)*24
			(*TJsonParent)(unsafe.Pointer(pParent)).FiHead = (*TJsonEachCursor)(unsafe.Pointer(p)).Fi
			(*TJsonParent)(unsafe.Pointer(pParent)).FiValue = i
			(*TJsonParent)(unsafe.Pointer(pParent)).FiEnd = i + n + **(**Tu32)(__ccgo_up(bp))
			(*TJsonParent)(unsafe.Pointer(pParent)).FiKey = int64(-int32(1))
			(*TJsonParent)(unsafe.Pointer(pParent)).FnPath = uint32((*TJsonEachCursor)(unsafe.Pointer(p)).Fpath.FnUsed)
			if (*TJsonEachCursor)(unsafe.Pointer(p)).FeType != 0 && (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent != 0 {
				_jsonAppendPathName(tls, p)
				if (*TJsonEachCursor)(unsafe.Pointer(p)).Fpath.FeErr != 0 {
					rc = int32(SQLITE_NOMEM)
				}
			}
			(*TJsonEachCursor)(unsafe.Pointer(p)).FnParent = (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent + 1
			(*TJsonEachCursor)(unsafe.Pointer(p)).Fi = i + n
		} else {
			(*TJsonEachCursor)(unsafe.Pointer(p)).Fi = i + n + **(**Tu32)(__ccgo_up(bp))
		}
		for (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent > uint32(0) && (*TJsonEachCursor)(unsafe.Pointer(p)).Fi >= (**(**TJsonParent)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent-uint32(1))*24))).FiEnd {
			(*TJsonEachCursor)(unsafe.Pointer(p)).FnParent = (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent - 1
			(*TJsonEachCursor)(unsafe.Pointer(p)).Fpath.FnUsed = uint64((**(**TJsonParent)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent)*24))).FnPath)
			levelChange = uint8(1)
		}
		if levelChange != 0 {
			if (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent > uint32(0) {
				pParent1 = (*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent-uint32(1))*24
				iVal = (*TJsonParent)(unsafe.Pointer(pParent1)).FiValue
				(*TJsonEachCursor)(unsafe.Pointer(p)).FeType = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FsParse.FaBlob + uintptr(iVal)))) & int32(0x0f))
			} else {
				(*TJsonEachCursor)(unsafe.Pointer(p)).FeType = uint8(0)
			}
		}
	} else {
		**(**Tu32)(__ccgo_up(bp + 4)) = uint32(0)
		i1 = libc.Uint32FromInt32(_jsonSkipLabel(tls, p))
		n1 = _jsonbPayloadSize(tls, p+168, i1, bp+4)
		(*TJsonEachCursor)(unsafe.Pointer(p)).Fi = i1 + n1 + **(**Tu32)(__ccgo_up(bp + 4))
	}
	if libc.Int32FromUint8((*TJsonEachCursor)(unsafe.Pointer(p)).FeType) == int32(JSONB_ARRAY) && (*TJsonEachCursor)(unsafe.Pointer(p)).FnParent != 0 {
		(**(**TJsonParent)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent-uint32(1))*24))).FiKey = (**(**TJsonParent)(__ccgo_up((*TJsonEachCursor)(unsafe.Pointer(p)).FaParent + uintptr((*TJsonEachCursor)(unsafe.Pointer(p)).FnParent-uint32(1))*24))).FiKey + 1
	}
	(*TJsonEachCursor)(unsafe.Pointer(p)).FiRowid = (*TJsonEachCursor)(unsafe.Pointer(p)).FiRowid + 1
	return rc
}

// C documentation
//
//	/*
//	** RFC-7396 MergePatch for two JSONB blobs.
//	**
//	** pTarget is the target. pPatch is the patch.  The target is updated
//	** in place.  The patch is read-only.
//	**
//	** The original RFC-7396 algorithm is this:
//	**
//	**   define MergePatch(Target, Patch):
//	**     if Patch is an Object:
//	**       if Target is not an Object:
//	**         Target = {} # Ignore the contents and set it to an empty Object
//	**     for each Name/Value pair in Patch:
//	**         if Value is null:
//	**           if Name exists in Target:
//	**             remove the Name/Value pair from Target
//	**         else:
//	**           Target[Name] = MergePatch(Target[Name], Value)
//	**       return Target
//	**     else:
//	**       return Patch
//	**
//	** Here is an equivalent algorithm restructured to show the actual
//	** implementation:
//	**
//	** 01   define MergePatch(Target, Patch):
//	** 02      if Patch is not an Object:
//	** 03         return Patch
//	** 04      else: // if Patch is an Object
//	** 05         if Target is not an Object:
//	** 06            Target = {}
//	** 07      for each Name/Value pair in Patch:
//	** 08         if Name exists in Target:
//	** 09            if Value is null:
//	** 10               remove the Name/Value pair from Target
//	** 11            else
//	** 12               Target[name] = MergePatch(Target[Name], Value)
//	** 13         else if Value is not NULL:
//	** 14            if Value is not an Object:
//	** 15               Target[name] = Value
//	** 16            else:
//	** 17               Target[name] = MergePatch('{}',value)
//	** 18      return Target
//	**  |
//	**  ^---- Line numbers referenced in comments in the implementation
//	*/
func _jsonMergePatch(tls *libc.TLS, pTarget uintptr, iTarget Tu32, pPatch uintptr, iPatch Tu32, iDepth Tu32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var ePLabel, eTLabel, x Tu8
	var iPCursor, iPEnd, iPLabel, iPValue, iTCursor, iTEnd, iTEndBE, iTLabel, iTStart, iTValue, n, nPLabel, nPValue, nTLabel, nTValue, szNew, szPatch, szTarget Tu32
	var isEqual, rc, rc1, savedDelta, savedDelta1, v1 int32
	var _ /* sz at bp+0 */ Tu32
	var _ /* szPLabel at bp+12 */ Tu32
	var _ /* szPValue at bp+16 */ Tu32
	var _ /* szTLabel at bp+4 */ Tu32
	var _ /* szTValue at bp+8 */ Tu32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = ePLabel, eTLabel, iPCursor, iPEnd, iPLabel, iPValue, iTCursor, iTEnd, iTEndBE, iTLabel, iTStart, iTValue, isEqual, n, nPLabel, nPValue, nTLabel, nTValue, rc, rc1, savedDelta, savedDelta1, szNew, szPatch, szTarget, x, v1
	**(**Tu32)(__ccgo_up(bp)) = uint32(0)     /* Node type of the target label */
	iTLabel = uint32(0)                       /* Index of the label */
	nTLabel = uint32(0)                       /* Header size in bytes for the target label */
	**(**Tu32)(__ccgo_up(bp + 4)) = uint32(0) /* Size of the target label payload */
	iTValue = uint32(0)                       /* Index of the target value */
	nTValue = uint32(0)                       /* Header size of the target value */
	**(**Tu32)(__ccgo_up(bp + 8)) = uint32(0) /* Payload size of the patch value */
	x = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob + uintptr(iPatch)))) & int32(0x0f))
	if libc.Int32FromUint8(x) != int32(JSONB_OBJECT) { /* Total size of the target, header+payload */
		n = _jsonbPayloadSize(tls, pPatch, iPatch, bp)
		szPatch = n + **(**Tu32)(__ccgo_up(bp))
		**(**Tu32)(__ccgo_up(bp)) = uint32(0)
		n = _jsonbPayloadSize(tls, pTarget, iTarget, bp)
		szTarget = n + **(**Tu32)(__ccgo_up(bp))
		_jsonBlobEdit(tls, pTarget, iTarget, szTarget, (*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob+uintptr(iPatch), szPatch)
		if (*TJsonParse)(unsafe.Pointer(pTarget)).Foom != 0 {
			v1 = int32(JSON_MERGE_OOM)
		} else {
			v1 = JSON_MERGE_OK
		}
		return v1 /* Line 03 */
	}
	x = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob + uintptr(iTarget)))) & int32(0x0f))
	if libc.Int32FromUint8(x) != int32(JSONB_OBJECT) { /* Algorithm line 05 */
		n = _jsonbPayloadSize(tls, pTarget, iTarget, bp)
		_jsonBlobEdit(tls, pTarget, iTarget+n, **(**Tu32)(__ccgo_up(bp)), uintptr(0), uint32(0))
		x = **(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob + uintptr(iTarget)))
		**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob + uintptr(iTarget))) = libc.Uint8FromInt32(libc.Int32FromUint8(x)&int32(0xf0) | int32(JSONB_OBJECT))
	}
	n = _jsonbPayloadSize(tls, pPatch, iPatch, bp)
	if n == uint32(0) {
		return int32(JSON_MERGE_BADPATCH)
	}
	iPCursor = iPatch + n
	iPEnd = iPCursor + **(**Tu32)(__ccgo_up(bp))
	n = _jsonbPayloadSize(tls, pTarget, iTarget, bp)
	if n == uint32(0) {
		return int32(JSON_MERGE_BADTARGET)
	}
	iTStart = iTarget + n
	iTEndBE = iTStart + **(**Tu32)(__ccgo_up(bp))
	for iPCursor < iPEnd { /* Algorithm line 07 */
		iPLabel = iPCursor
		ePLabel = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob + uintptr(iPCursor)))) & int32(0x0f))
		if libc.Int32FromUint8(ePLabel) < int32(JSONB_TEXT) || libc.Int32FromUint8(ePLabel) > int32(JSONB_TEXTRAW) {
			return int32(JSON_MERGE_BADPATCH)
		}
		nPLabel = _jsonbPayloadSize(tls, pPatch, iPCursor, bp+12)
		if nPLabel == uint32(0) {
			return int32(JSON_MERGE_BADPATCH)
		}
		iPValue = iPCursor + nPLabel + **(**Tu32)(__ccgo_up(bp + 12))
		if iPValue >= iPEnd {
			return int32(JSON_MERGE_BADPATCH)
		}
		nPValue = _jsonbPayloadSize(tls, pPatch, iPValue, bp+16)
		if nPValue == uint32(0) {
			return int32(JSON_MERGE_BADPATCH)
		}
		iPCursor = iPValue + nPValue + **(**Tu32)(__ccgo_up(bp + 16))
		if iPCursor > iPEnd {
			return int32(JSON_MERGE_BADPATCH)
		}
		iTCursor = iTStart
		iTEnd = iTEndBE + libc.Uint32FromInt32((*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta)
		for iTCursor < iTEnd { /* true if the patch and target labels match */
			iTLabel = iTCursor
			eTLabel = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob + uintptr(iTCursor)))) & int32(0x0f))
			if libc.Int32FromUint8(eTLabel) < int32(JSONB_TEXT) || libc.Int32FromUint8(eTLabel) > int32(JSONB_TEXTRAW) {
				return int32(JSON_MERGE_BADTARGET)
			}
			nTLabel = _jsonbPayloadSize(tls, pTarget, iTCursor, bp+4)
			if nTLabel == uint32(0) {
				return int32(JSON_MERGE_BADTARGET)
			}
			iTValue = iTLabel + nTLabel + **(**Tu32)(__ccgo_up(bp + 4))
			if iTValue >= iTEnd {
				return int32(JSON_MERGE_BADTARGET)
			}
			nTValue = _jsonbPayloadSize(tls, pTarget, iTValue, bp+8)
			if nTValue == uint32(0) {
				return int32(JSON_MERGE_BADTARGET)
			}
			if iTValue+nTValue+**(**Tu32)(__ccgo_up(bp + 8)) > iTEnd {
				return int32(JSON_MERGE_BADTARGET)
			}
			isEqual = _jsonLabelCompare(tls, (*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob+uintptr(iPLabel+nPLabel), **(**Tu32)(__ccgo_up(bp + 12)), libc.BoolInt32(libc.Int32FromUint8(ePLabel) == int32(JSONB_TEXT) || libc.Int32FromUint8(ePLabel) == int32(JSONB_TEXTRAW)), (*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob+uintptr(iTLabel+nTLabel), **(**Tu32)(__ccgo_up(bp + 4)), libc.BoolInt32(libc.Int32FromUint8(eTLabel) == int32(JSONB_TEXT) || libc.Int32FromUint8(eTLabel) == int32(JSONB_TEXTRAW)))
			if isEqual != 0 {
				break
			}
			iTCursor = iTValue + nTValue + **(**Tu32)(__ccgo_up(bp + 8))
		}
		x = libc.Uint8FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob + uintptr(iPValue)))) & int32(0x0f))
		if iTCursor < iTEnd {
			/* A match was found.  Algorithm line 08 */
			if libc.Int32FromUint8(x) == 0 {
				/* Patch value is NULL.  Algorithm line 09 */
				_jsonBlobEdit(tls, pTarget, iTLabel, nTLabel+**(**Tu32)(__ccgo_up(bp + 4))+nTValue+**(**Tu32)(__ccgo_up(bp + 8)), uintptr(0), uint32(0))
				/*  vvvvvv----- No OOM on a delete-only edit */
				if (*TJsonParse)(unsafe.Pointer(pTarget)).Foom != 0 {
					return int32(JSON_MERGE_OOM)
				}
			} else {
				savedDelta = (*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta
				(*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta = 0
				if iDepth >= uint32(JSON_MAX_DEPTH) {
					return int32(JSON_MERGE_TOODEEP)
				}
				rc = _jsonMergePatch(tls, pTarget, iTValue, pPatch, iPValue, iDepth+uint32(1))
				if rc != 0 {
					return rc
				}
				**(**int32)(__ccgo_up(pTarget + 40)) += savedDelta
			}
		} else {
			if libc.Int32FromUint8(x) > 0 { /* Algorithm line 13 */
				/* No match and patch value is not NULL */
				szNew = **(**Tu32)(__ccgo_up(bp + 12)) + nPLabel
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob + uintptr(iPValue))))&int32(0x0f) != int32(JSONB_OBJECT) { /* Line 14 */
					_jsonBlobEdit(tls, pTarget, iTEnd, uint32(0), uintptr(0), **(**Tu32)(__ccgo_up(bp + 16))+nPValue+szNew)
					if (*TJsonParse)(unsafe.Pointer(pTarget)).Foom != 0 {
						return int32(JSON_MERGE_OOM)
					}
					libc.Xmemcpy(tls, (*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob+uintptr(iTEnd), (*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob+uintptr(iPLabel), szNew)
					libc.Xmemcpy(tls, (*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob+uintptr(iTEnd+szNew), (*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob+uintptr(iPValue), **(**Tu32)(__ccgo_up(bp + 16))+nPValue)
				} else {
					_jsonBlobEdit(tls, pTarget, iTEnd, uint32(0), uintptr(0), szNew+uint32(1))
					if (*TJsonParse)(unsafe.Pointer(pTarget)).Foom != 0 {
						return int32(JSON_MERGE_OOM)
					}
					libc.Xmemcpy(tls, (*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob+uintptr(iTEnd), (*TJsonParse)(unsafe.Pointer(pPatch)).FaBlob+uintptr(iPLabel), szNew)
					**(**Tu8)(__ccgo_up((*TJsonParse)(unsafe.Pointer(pTarget)).FaBlob + uintptr(iTEnd+szNew))) = uint8(0x00)
					savedDelta1 = (*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta
					(*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta = 0
					if iDepth >= uint32(JSON_MAX_DEPTH) {
						return int32(JSON_MERGE_TOODEEP)
					}
					rc1 = _jsonMergePatch(tls, pTarget, iTEnd+szNew, pPatch, iPValue, iDepth+uint32(1))
					if rc1 != 0 {
						return rc1
					}
					**(**int32)(__ccgo_up(pTarget + 40)) += savedDelta1
				}
			}
		}
	}
	if (*TJsonParse)(unsafe.Pointer(pTarget)).Fdelta != 0 {
		_jsonAfterEditSizeAdjust(tls, pTarget, iTarget)
	}
	if (*TJsonParse)(unsafe.Pointer(pTarget)).Foom != 0 {
		v1 = int32(JSON_MERGE_OOM)
	} else {
		v1 = JSON_MERGE_OK
	}
	return v1
}

// C documentation
//
//	/* Append formatted text (not to exceed N bytes) to the JsonString.
//	*/
func _jsonPrintf(tls *libc.TLS, N int32, p uintptr, zFormat uintptr, va uintptr) {
	var ap Tva_list
	_ = ap
	if (*TJsonString)(unsafe.Pointer(p)).FnUsed+libc.Uint64FromInt32(N) >= (*TJsonString)(unsafe.Pointer(p)).FnAlloc && _jsonStringGrow(tls, p, libc.Uint32FromInt32(N)) != 0 {
		return
	}
	ap = va
	Xsqlite3_vsnprintf(tls, N, (*TJsonString)(unsafe.Pointer(p)).FzBuf+uintptr((*TJsonString)(unsafe.Pointer(p)).FnUsed), zFormat, ap)
	_ = ap
	**(**Tu64)(__ccgo_up(p + 16)) += libc.Uint64FromInt32(libc.Int32FromUint32(libc.Xstrlen(tls, (*TJsonString)(unsafe.Pointer(p)).FzBuf+uintptr((*TJsonString)(unsafe.Pointer(p)).FnUsed))))
}

// C documentation
//
//	/*
//	** Make the return value of a JSON function either the raw JSONB blob
//	** or make it JSON text, depending on whether the JSON_BLOB flag is
//	** set on the function.
//	*/
func _jsonReturnParse(tls *libc.TLS, ctx uintptr, p uintptr) {
	bp := tls.Alloc(128)
	defer tls.Free(128)
	var flgs int32
	var _ /* s at bp+0 */ TJsonString
	_ = flgs
	if (*TJsonParse)(unsafe.Pointer(p)).Foom != 0 {
		Xsqlite3_result_error_nomem(tls, ctx)
		return
	}
	flgs = int32(Xsqlite3_user_data(tls, ctx))
	if flgs&int32(JSON_BLOB) != 0 {
		if (*TJsonParse)(unsafe.Pointer(p)).FnBlobAlloc > uint32(0) && !((*TJsonParse)(unsafe.Pointer(p)).FbReadOnly != 0) {
			Xsqlite3_result_blob(tls, ctx, (*TJsonParse)(unsafe.Pointer(p)).FaBlob, libc.Int32FromUint32((*TJsonParse)(unsafe.Pointer(p)).FnBlob), __ccgo_fp(_sqlite3RowSetClear))
			(*TJsonParse)(unsafe.Pointer(p)).FnBlobAlloc = uint32(0)
		} else {
			Xsqlite3_result_blob(tls, ctx, (*TJsonParse)(unsafe.Pointer(p)).FaBlob, libc.Int32FromUint32((*TJsonParse)(unsafe.Pointer(p)).FnBlob), uintptr(-libc.Int32FromInt32(1)))
		}
	} else {
		_jsonStringInit(tls, bp, ctx)
		(*TJsonParse)(unsafe.Pointer(p)).Fdelta = 0
		_jsonTranslateBlobToText(tls, p, uint32(0), bp)
		_jsonReturnString(tls, bp, p, ctx)
		Xsqlite3_result_subtype(tls, ctx, uint32(JSON_SUBTYPE))
	}
}

/****************************************************************************
** SQL functions used for testing and debugging
****************************************************************************/

/****************************************************************************
** Scalar SQL function implementations
****************************************************************************/

// C documentation
//
//	/*
//	** The input string pStr is a well-formed JSON text string.  Convert
//	** this into the JSONB format and make it the return value of the
//	** SQL function.
//	*/
func _jsonReturnStringAsBlob(tls *libc.TLS, pStr uintptr) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var _ /* px at bp+0 */ TJsonParse
	libc.Xmemset(tls, bp, 0, uint32(56))
	(**(**TJsonParse)(__ccgo_up(bp))).FzJson = (*TJsonString)(unsafe.Pointer(pStr)).FzBuf
	(**(**TJsonParse)(__ccgo_up(bp))).FnJson = libc.Int32FromUint64((*TJsonString)(unsafe.Pointer(pStr)).FnUsed)
	(**(**TJsonParse)(__ccgo_up(bp))).Fdb = Xsqlite3_context_db_handle(tls, (*TJsonString)(unsafe.Pointer(pStr)).FpCtx)
	_jsonTranslateTextToBlob(tls, bp, uint32(0))
	if (**(**TJsonParse)(__ccgo_up(bp))).Foom != 0 {
		_sqlite3DbFree(tls, (**(**TJsonParse)(__ccgo_up(bp))).Fdb, (**(**TJsonParse)(__ccgo_up(bp))).FaBlob)
		Xsqlite3_result_error_nomem(tls, (*TJsonString)(unsafe.Pointer(pStr)).FpCtx)
	} else {
		Xsqlite3_result_blob(tls, (*TJsonString)(unsafe.Pointer(pStr)).FpCtx, (**(**TJsonParse)(__ccgo_up(bp))).FaBlob, libc.Int32FromUint32((**(**TJsonParse)(__ccgo_up(bp))).FnBlob), __ccgo_fp(_sqlite3RowSetClear))
	}
}

// C documentation
//
//	/*
//	** json_set(JSON, PATH, VALUE, ...)
//	**
//	** Set the value at PATH to VALUE.  Create the PATH if it does not already
//	** exist.  Overwrite existing values that do exist.
//	** If JSON or PATH is malformed, throw an error.
//	**
//	** json_insert(JSON, PATH, VALUE, ...)
//	**
//	** Create PATH and initialize it to VALUE.  If PATH already exists, this
//	** routine is a no-op.  If JSON or PATH is malformed, throw an error.
//	*/
func _jsonSetFunc(tls *libc.TLS, ctx uintptr, argc int32, argv uintptr) {
	var eInsType, flags int32
	_, _ = eInsType, flags
	flags = int32(Xsqlite3_user_data(tls, ctx))
	eInsType = flags & int32(0xC) >> int32(2)
	if argc < int32(1) {
		return
	}
	if argc&int32(1) == 0 {
		_jsonWrongNumArgs(tls, ctx, _azInsType[eInsType])
		return
	}
	_jsonInsertIntoBlob(tls, ctx, argc, argv, libc.Int32FromUint8(_aEditType[eInsType]))
}

// C documentation
//
//	/*
//	** If the cursor is currently pointing at the label of a object entry,
//	** then return the index of the value.  For all other cases, return the
//	** current pointer position, which is the value.
//	*/
func _jsonSkipLabel(tls *libc.TLS, p uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var n Tu32
	var _ /* sz at bp+0 */ Tu32
	_ = n
	if libc.Int32FromUint8((*TJsonEachCursor)(unsafe.Pointer(p)).FeType) == int32(JSONB_OBJECT) {
		**(**Tu32)(__ccgo_up(bp)) = uint32(0)
		n = _jsonbPayloadSize(tls, p+168, (*TJsonEachCursor)(unsafe.Pointer(p)).Fi, bp)
		return libc.Int32FromUint32((*TJsonEachCursor)(unsafe.Pointer(p)).Fi + n + **(**Tu32)(__ccgo_up(bp)))
	} else {
		return libc.Int32FromUint32((*TJsonEachCursor)(unsafe.Pointer(p)).Fi)
	}
	return r
}

// C documentation
//
//	/*
//	** Implementation of the length() function
//	*/
func _lengthFunc(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	var c, v1 uint8
	var z, z0 uintptr
	_, _, _, _ = c, z, z0, v1
	_ = argc
	switch Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(argv))) {
	case int32(SQLITE_BLOB):
		fallthrough
	case int32(SQLITE_INTEGER):
		fallthrough
	case int32(SQLITE_FLOAT):
		Xsqlite3_result_int(tls, context, Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(argv))))
	case int32(SQLITE_TEXT):
		z = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
		if z == uintptr(0) {
			return
		}
		z0 = z
		for {
			v1 = **(**uint8)(__ccgo_up(z))
			c = v1
			if !(libc.Int32FromUint8(v1) != 0) {
				break
			}
			z = z + 1
			if libc.Int32FromUint8(c) >= int32(0xc0) {
				for libc.Int32FromUint8(**(**uint8)(__ccgo_up(z)))&int32(0xc0) == int32(0x80) {
					z = z + 1
					z0 = z0 + 1
				}
			}
		}
		Xsqlite3_result_int(tls, context, int32(z)-int32(z0))
	default:
		Xsqlite3_result_null(tls, context)
		break
	}
}

// C documentation
//
//	/*
//	** Load the content from either the sqlite_stat4
//	** into the relevant Index.aSample[] arrays.
//	**
//	** Arguments zSql1 and zSql2 must point to SQL statements that return
//	** data equivalent to the following:
//	**
//	**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
//	**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
//	**
//	** where %Q is replaced with the database name before the SQL is executed.
//	*/
func _loadStatTbl(tls *libc.TLS, db uintptr, zSql1 uintptr, zSql2 uintptr, zDb uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var i, nByte Ti64
	var nCol, nIdxCol, nSample, rc int32
	var pIdx, pIdx1, pPrevIdx, pPtr, pSample, pSpace, zIndex, zIndex1, zSql uintptr
	var _ /* pStmt at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = i, nByte, nCol, nIdxCol, nSample, pIdx, pIdx1, pPrevIdx, pPtr, pSample, pSpace, rc, zIndex, zIndex1, zSql /* Result codes from subroutines */
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)                                                                                                               /* Text of the SQL statement */
	pPrevIdx = uintptr(0)                                                                                                                                   /* A slot in pIdx->aSample[] */
	zSql = _sqlite3MPrintf(tls, db, zSql1, libc.VaList(bp+16, zDb))
	if !(zSql != 0) {
		return int32(SQLITE_NOMEM)
	}
	rc = Xsqlite3_prepare(tls, db, zSql, -int32(1), bp, uintptr(0))
	_sqlite3DbFree(tls, db, zSql)
	if rc != 0 {
		return rc
	}
	for Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp))) == int32(SQLITE_ROW) {
		nIdxCol = int32(1) /* Available memory as a u8 for easier manipulation */
		zIndex = Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), 0)
		if zIndex == uintptr(0) {
			continue
		}
		nSample = Xsqlite3_column_int(tls, **(**uintptr)(__ccgo_up(bp)), int32(1))
		pIdx = _findIndexOrPrimaryKey(tls, db, zIndex, zDb)
		if pIdx == uintptr(0) {
			continue
		}
		if (*TIndex)(unsafe.Pointer(pIdx)).FaSample != uintptr(0) {
			/* The same index appears in sqlite_stat4 under multiple names */
			continue
		}
		if !((*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) && int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x3>>0)) == int32(SQLITE_IDXTYPE_PRIMARYKEY) {
			nIdxCol = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
		} else {
			nIdxCol = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
		}
		(*TIndex)(unsafe.Pointer(pIdx)).FnSampleCol = nIdxCol
		(*TIndex)(unsafe.Pointer(pIdx)).FmxSample = nSample
		nByte = (libc.Int64FromInt64(20)*int64(nSample) + libc.Int64FromInt32(7)) & int64(^libc.Int32FromInt32(7))
		nByte = nByte + libc.Int64FromInt64(8)*int64(nIdxCol)*int64(3)*int64(nSample)
		nByte = nByte + int64(nIdxCol)*libc.Int64FromInt64(8) /* Space for Index.aAvgEq[] */
		(*TIndex)(unsafe.Pointer(pIdx)).FaSample = _sqlite3DbMallocZero(tls, db, libc.Uint64FromInt64(nByte))
		if (*TIndex)(unsafe.Pointer(pIdx)).FaSample == uintptr(0) {
			Xsqlite3_finalize(tls, **(**uintptr)(__ccgo_up(bp)))
			return int32(SQLITE_NOMEM)
		}
		pPtr = (*TIndex)(unsafe.Pointer(pIdx)).FaSample
		pPtr = pPtr + uintptr((int64(nSample)*libc.Int64FromInt64(20)+libc.Int64FromInt32(7))&int64(^libc.Int32FromInt32(7)))
		pSpace = pPtr
		(*TIndex)(unsafe.Pointer(pIdx)).FaAvgEq = pSpace
		pSpace = pSpace + uintptr(nIdxCol)*8
		**(**Tu32)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FpTable + 28)) |= uint32(TF_HasStat4)
		i = 0
		for {
			if !(i < int64(nSample)) {
				break
			}
			(**(**TIndexSample)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaSample + uintptr(i)*20))).FanEq = pSpace
			pSpace = pSpace + uintptr(nIdxCol)*8
			(**(**TIndexSample)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaSample + uintptr(i)*20))).FanLt = pSpace
			pSpace = pSpace + uintptr(nIdxCol)*8
			(**(**TIndexSample)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaSample + uintptr(i)*20))).FanDLt = pSpace
			pSpace = pSpace + uintptr(nIdxCol)*8
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	rc = Xsqlite3_finalize(tls, **(**uintptr)(__ccgo_up(bp)))
	if rc != 0 {
		return rc
	}
	zSql = _sqlite3MPrintf(tls, db, zSql2, libc.VaList(bp+16, zDb))
	if !(zSql != 0) {
		return int32(SQLITE_NOMEM)
	}
	rc = Xsqlite3_prepare(tls, db, zSql, -int32(1), bp, uintptr(0))
	_sqlite3DbFree(tls, db, zSql)
	if rc != 0 {
		return rc
	}
	for Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp))) == int32(SQLITE_ROW) { /* Pointer to the index object */
		nCol = int32(1) /* Number of columns in index */
		zIndex1 = Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), 0)
		if zIndex1 == uintptr(0) {
			continue
		}
		pIdx1 = _findIndexOrPrimaryKey(tls, db, zIndex1, zDb)
		if pIdx1 == uintptr(0) {
			continue
		}
		if (*TIndex)(unsafe.Pointer(pIdx1)).FnSample >= (*TIndex)(unsafe.Pointer(pIdx1)).FmxSample {
			/* Too many slots used because the same index appears in
			 ** sqlite_stat4 using multiple names */
			continue
		}
		/* This next condition is true if data has already been loaded from
		 ** the sqlite_stat4 table. */
		nCol = (*TIndex)(unsafe.Pointer(pIdx1)).FnSampleCol
		if pIdx1 != pPrevIdx {
			_initAvgEq(tls, pPrevIdx)
			pPrevIdx = pIdx1
		}
		pSample = (*TIndex)(unsafe.Pointer(pIdx1)).FaSample + uintptr((*TIndex)(unsafe.Pointer(pIdx1)).FnSample)*20
		_decodeIntArray(tls, Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), int32(1)), nCol, (*TIndexSample)(unsafe.Pointer(pSample)).FanEq, uintptr(0), uintptr(0))
		_decodeIntArray(tls, Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), int32(2)), nCol, (*TIndexSample)(unsafe.Pointer(pSample)).FanLt, uintptr(0), uintptr(0))
		_decodeIntArray(tls, Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp)), int32(3)), nCol, (*TIndexSample)(unsafe.Pointer(pSample)).FanDLt, uintptr(0), uintptr(0))
		/* Take a copy of the sample. Add 8 extra 0x00 bytes the end of the buffer.
		 ** This is in case the sample record is corrupted. In that case, the
		 ** sqlite3VdbeRecordCompare() may read up to two varints past the
		 ** end of the allocated buffer before it realizes it is dealing with
		 ** a corrupt record.  Or it might try to read a large integer from the
		 ** buffer.  In any case, eight 0x00 bytes prevents this from causing
		 ** a buffer overread.  */
		(*TIndexSample)(unsafe.Pointer(pSample)).Fn = Xsqlite3_column_bytes(tls, **(**uintptr)(__ccgo_up(bp)), int32(4))
		(*TIndexSample)(unsafe.Pointer(pSample)).Fp = _sqlite3DbMallocZero(tls, db, libc.Uint64FromInt32((*TIndexSample)(unsafe.Pointer(pSample)).Fn+int32(8)))
		if (*TIndexSample)(unsafe.Pointer(pSample)).Fp == uintptr(0) {
			Xsqlite3_finalize(tls, **(**uintptr)(__ccgo_up(bp)))
			return int32(SQLITE_NOMEM)
		}
		if (*TIndexSample)(unsafe.Pointer(pSample)).Fn != 0 {
			libc.Xmemcpy(tls, (*TIndexSample)(unsafe.Pointer(pSample)).Fp, Xsqlite3_column_blob(tls, **(**uintptr)(__ccgo_up(bp)), int32(4)), libc.Uint32FromInt32((*TIndexSample)(unsafe.Pointer(pSample)).Fn))
		}
		(*TIndex)(unsafe.Pointer(pIdx1)).FnSample = (*TIndex)(unsafe.Pointer(pIdx1)).FnSample + 1
	}
	rc = Xsqlite3_finalize(tls, **(**uintptr)(__ccgo_up(bp)))
	if rc == SQLITE_OK {
		_initAvgEq(tls, pPrevIdx)
	}
	return rc
}

// C documentation
//
//	/*
//	** Record the fact that we want to lock a table at run-time.
//	**
//	** The table to be locked has root page iTab and is found in database iDb.
//	** A read or a write lock can be taken depending on isWritelock.
//	**
//	** This routine just records the fact that the lock is desired.  The
//	** code to make the lock occur is generated by a later call to
//	** codeTableLocks() which occurs during sqlite3FinishCoding().
//	*/
func _lockTable(tls *libc.TLS, pParse uintptr, iDb int32, iTab TPgno, isWriteLock Tu8, zName uintptr) {
	var i, nBytes, v3 int32
	var p, pToplevel, v1 uintptr
	_, _, _, _, _, _ = i, nBytes, p, pToplevel, v1, v3
	if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
		v1 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
	} else {
		v1 = pParse
	}
	pToplevel = v1
	i = 0
	for {
		if !(i < (*TParse)(unsafe.Pointer(pToplevel)).FnTableLock) {
			break
		}
		p = (*TParse)(unsafe.Pointer(pToplevel)).FaTableLock + uintptr(i)*16
		if (*TTableLock)(unsafe.Pointer(p)).FiDb == iDb && (*TTableLock)(unsafe.Pointer(p)).FiTab == iTab {
			(*TTableLock)(unsafe.Pointer(p)).FisWriteLock = libc.BoolUint8((*TTableLock)(unsafe.Pointer(p)).FisWriteLock != 0 || isWriteLock != 0)
			return
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	nBytes = libc.Int32FromUint32(uint32(16) * libc.Uint32FromInt32((*TParse)(unsafe.Pointer(pToplevel)).FnTableLock+libc.Int32FromInt32(1)))
	(*TParse)(unsafe.Pointer(pToplevel)).FaTableLock = _sqlite3DbReallocOrFree(tls, (*TParse)(unsafe.Pointer(pToplevel)).Fdb, (*TParse)(unsafe.Pointer(pToplevel)).FaTableLock, libc.Uint64FromInt32(nBytes))
	if (*TParse)(unsafe.Pointer(pToplevel)).FaTableLock != 0 {
		v1 = pToplevel + 108
		v3 = *(*int32)(unsafe.Pointer(v1))
		*(*int32)(unsafe.Pointer(v1)) = *(*int32)(unsafe.Pointer(v1)) + 1
		p = (*TParse)(unsafe.Pointer(pToplevel)).FaTableLock + uintptr(v3)*16
		(*TTableLock)(unsafe.Pointer(p)).FiDb = iDb
		(*TTableLock)(unsafe.Pointer(p)).FiTab = iTab
		(*TTableLock)(unsafe.Pointer(p)).FisWriteLock = isWriteLock
		(*TTableLock)(unsafe.Pointer(p)).FzLockName = zName
	} else {
		(*TParse)(unsafe.Pointer(pToplevel)).FnTableLock = 0
		_sqlite3OomFault(tls, (*TParse)(unsafe.Pointer(pToplevel)).Fdb)
	}
}

// C documentation
//
//	/*
//	** Read data from an memdb-file.
//	*/
func _memdbRead(tls *libc.TLS, pFile uintptr, zBuf uintptr, iAmt int32, iOfst Tsqlite_int64) (r int32) {
	var p uintptr
	_ = p
	p = (*TMemFile)(unsafe.Pointer(pFile)).FpStore
	_memdbEnter(tls, p)
	if iOfst+int64(iAmt) > (*TMemStore)(unsafe.Pointer(p)).Fsz {
		libc.Xmemset(tls, zBuf, 0, libc.Uint32FromInt32(iAmt))
		if iOfst < (*TMemStore)(unsafe.Pointer(p)).Fsz {
			libc.Xmemcpy(tls, zBuf, (*TMemStore)(unsafe.Pointer(p)).FaData+uintptr(iOfst), libc.Uint32FromInt64((*TMemStore)(unsafe.Pointer(p)).Fsz-iOfst))
		}
		_memdbLeave(tls, p)
		return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
	}
	libc.Xmemcpy(tls, zBuf, (*TMemStore)(unsafe.Pointer(p)).FaData+uintptr(iOfst), libc.Uint32FromInt32(iAmt))
	_memdbLeave(tls, p)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Write data to an memdb-file.
//	*/
func _memdbWrite(tls *libc.TLS, pFile uintptr, z uintptr, iAmt int32, iOfst Tsqlite_int64) (r int32) {
	var p uintptr
	var rc, v1 int32
	var v2 bool
	_, _, _, _ = p, rc, v1, v2
	p = (*TMemFile)(unsafe.Pointer(pFile)).FpStore
	_memdbEnter(tls, p)
	if (*TMemStore)(unsafe.Pointer(p)).FmFlags&uint32(SQLITE_DESERIALIZE_READONLY) != 0 {
		/* Can't happen: memdbLock() will return SQLITE_READONLY before
		 ** reaching this point */
		_memdbLeave(tls, p)
		return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(3)<<libc.Int32FromInt32(8)
	}
	if iOfst+int64(iAmt) > (*TMemStore)(unsafe.Pointer(p)).Fsz {
		if v2 = iOfst+int64(iAmt) > (*TMemStore)(unsafe.Pointer(p)).FszAlloc; v2 {
			v1 = _memdbEnlarge(tls, p, iOfst+int64(iAmt))
			rc = v1
		}
		if v2 && v1 != SQLITE_OK {
			_memdbLeave(tls, p)
			return rc
		}
		if iOfst > (*TMemStore)(unsafe.Pointer(p)).Fsz {
			libc.Xmemset(tls, (*TMemStore)(unsafe.Pointer(p)).FaData+uintptr((*TMemStore)(unsafe.Pointer(p)).Fsz), 0, libc.Uint32FromInt64(iOfst-(*TMemStore)(unsafe.Pointer(p)).Fsz))
		}
		(*TMemStore)(unsafe.Pointer(p)).Fsz = iOfst + int64(iAmt)
	}
	libc.Xmemcpy(tls, (*TMemStore)(unsafe.Pointer(p)).FaData+uintptr(iOfst), z, libc.Uint32FromInt32(iAmt))
	_memdbLeave(tls, p)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Read data from the in-memory journal file.  This is the implementation
//	** of the sqlite3_vfs.xRead method.
//	*/
func _memjrnlRead(tls *libc.TLS, pJfd uintptr, zBuf uintptr, iAmt int32, iOfst Tsqlite_int64) (r int32) {
	var iChunkOffset, iSpace, nCopy, nRead, v5 int32
	var iOff Tsqlite3_int64
	var p, pChunk, zOut, v2 uintptr
	var v3 bool
	var v6 int64
	_, _, _, _, _, _, _, _, _, _, _, _ = iChunkOffset, iOff, iSpace, nCopy, nRead, p, pChunk, zOut, v2, v3, v5, v6
	p = pJfd
	zOut = zBuf
	nRead = iAmt
	if int64(iAmt)+iOfst > (*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FiOffset {
		return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
	}
	if (*TMemJournal)(unsafe.Pointer(p)).Freadpoint.FiOffset != iOfst || iOfst == 0 {
		iOff = 0
		pChunk = (*TMemJournal)(unsafe.Pointer(p)).FpFirst
		for {
			if !(pChunk != 0 && iOff+int64((*TMemJournal)(unsafe.Pointer(p)).FnChunkSize) <= iOfst) {
				break
			}
			iOff = iOff + int64((*TMemJournal)(unsafe.Pointer(p)).FnChunkSize)
			goto _1
		_1:
			;
			pChunk = (*TFileChunk)(unsafe.Pointer(pChunk)).FpNext
		}
	} else {
		pChunk = (*TMemJournal)(unsafe.Pointer(p)).Freadpoint.FpChunk
	}
	iChunkOffset = int32(iOfst % int64((*TMemJournal)(unsafe.Pointer(p)).FnChunkSize))
	for {
		iSpace = (*TMemJournal)(unsafe.Pointer(p)).FnChunkSize - iChunkOffset
		if nRead < (*TMemJournal)(unsafe.Pointer(p)).FnChunkSize-iChunkOffset {
			v5 = nRead
		} else {
			v5 = (*TMemJournal)(unsafe.Pointer(p)).FnChunkSize - iChunkOffset
		}
		nCopy = v5
		libc.Xmemcpy(tls, zOut, pChunk+4+uintptr(iChunkOffset), libc.Uint32FromInt32(nCopy))
		zOut = zOut + uintptr(nCopy)
		nRead = nRead - iSpace
		iChunkOffset = 0
		goto _4
	_4:
		;
		if v3 = nRead >= 0; v3 {
			v2 = (*TFileChunk)(unsafe.Pointer(pChunk)).FpNext
			pChunk = v2
		}
		if !(v3 && v2 != uintptr(0) && nRead > 0) {
			break
		}
	}
	if pChunk != 0 {
		v6 = iOfst + int64(iAmt)
	} else {
		v6 = 0
	}
	(*TMemJournal)(unsafe.Pointer(p)).Freadpoint.FiOffset = v6
	(*TMemJournal)(unsafe.Pointer(p)).Freadpoint.FpChunk = pChunk
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Write data to the file.
//	*/
func _memjrnlWrite(tls *libc.TLS, pJfd uintptr, zBuf uintptr, iAmt int32, iOfst Tsqlite_int64) (r int32) {
	var iChunkOffset, iSpace, nWrite, rc, v1 int32
	var p, pChunk, pNew, zWrite, v2 uintptr
	_, _, _, _, _, _, _, _, _, _ = iChunkOffset, iSpace, nWrite, p, pChunk, pNew, rc, zWrite, v1, v2
	p = pJfd
	nWrite = iAmt
	zWrite = zBuf
	/* If the file should be created now, create it and write the new data
	 ** into the file on disk. */
	if (*TMemJournal)(unsafe.Pointer(p)).FnSpill > 0 && int64(iAmt)+iOfst > int64((*TMemJournal)(unsafe.Pointer(p)).FnSpill) {
		rc = _memjrnlCreateFile(tls, p)
		if rc == SQLITE_OK {
			rc = _sqlite3OsWrite(tls, pJfd, zBuf, iAmt, iOfst)
		}
		return rc
	} else {
		/* An in-memory journal file should only ever be appended to. Random
		 ** access writes are not required. The only exception to this is when
		 ** the in-memory journal is being used by a connection using the
		 ** atomic-write optimization. In this case the first 28 bytes of the
		 ** journal file may be written as part of committing the transaction. */
		if iOfst > 0 && iOfst != (*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FiOffset {
			_memjrnlTruncate(tls, pJfd, iOfst)
		}
		if iOfst == 0 && (*TMemJournal)(unsafe.Pointer(p)).FpFirst != 0 {
			libc.Xmemcpy(tls, (*TMemJournal)(unsafe.Pointer(p)).FpFirst+4, zBuf, libc.Uint32FromInt32(iAmt))
		} else {
			for nWrite > 0 {
				pChunk = (*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FpChunk
				iChunkOffset = int32((*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FiOffset % int64((*TMemJournal)(unsafe.Pointer(p)).FnChunkSize))
				if nWrite < (*TMemJournal)(unsafe.Pointer(p)).FnChunkSize-iChunkOffset {
					v1 = nWrite
				} else {
					v1 = (*TMemJournal)(unsafe.Pointer(p)).FnChunkSize - iChunkOffset
				}
				iSpace = v1
				if iChunkOffset == 0 {
					/* New chunk is required to extend the file. */
					pNew = Xsqlite3_malloc(tls, libc.Int32FromUint32(libc.Uint32FromInt64(12)+libc.Uint32FromInt32((*TMemJournal)(unsafe.Pointer(p)).FnChunkSize-libc.Int32FromInt32(8))))
					if !(pNew != 0) {
						return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(12)<<libc.Int32FromInt32(8)
					}
					(*TFileChunk)(unsafe.Pointer(pNew)).FpNext = uintptr(0)
					if pChunk != 0 {
						(*TFileChunk)(unsafe.Pointer(pChunk)).FpNext = pNew
					} else {
						(*TMemJournal)(unsafe.Pointer(p)).FpFirst = pNew
					}
					v2 = pNew
					(*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FpChunk = v2
					pChunk = v2
				}
				libc.Xmemcpy(tls, pChunk+4+uintptr(iChunkOffset), zWrite, libc.Uint32FromInt32(iSpace))
				zWrite = zWrite + uintptr(iSpace)
				nWrite = nWrite - iSpace
				(*TMemJournal)(unsafe.Pointer(p)).Fendpoint.FiOffset += int64(iSpace)
			}
		}
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** The select statement passed as the second parameter is a compound SELECT
//	** with an ORDER BY clause. This function allocates and returns a KeyInfo
//	** structure suitable for implementing the ORDER BY.
//	**
//	** Space to hold the KeyInfo structure is obtained from malloc. The calling
//	** function is responsible for ensuring that this structure is eventually
//	** freed.
//	*/
func _multiSelectByMergeKeyInfo(tls *libc.TLS, pParse uintptr, p uintptr, nExtra int32) (r uintptr) {
	var db, pColl, pItem, pOrderBy, pRet, pTerm uintptr
	var i, nOrderBy, v1 int32
	_, _, _, _, _, _, _, _, _ = db, i, nOrderBy, pColl, pItem, pOrderBy, pRet, pTerm, v1
	pOrderBy = (*TSelect)(unsafe.Pointer(p)).FpOrderBy
	if pOrderBy != uintptr(0) {
		v1 = (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr
	} else {
		v1 = 0
	}
	nOrderBy = v1
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	pRet = _sqlite3KeyInfoAlloc(tls, db, nOrderBy+nExtra, int32(1))
	if pRet != 0 {
		i = 0
		for {
			if !(i < nOrderBy) {
				break
			}
			pItem = pOrderBy + 8 + uintptr(i)*20
			pTerm = (*TExprList_item)(unsafe.Pointer(pItem)).FpExpr
			if (*TExpr)(unsafe.Pointer(pTerm)).Fflags&uint32(EP_Collate) != 0 {
				pColl = _sqlite3ExprCollSeq(tls, pParse, pTerm)
			} else {
				pColl = _multiSelectCollSeq(tls, pParse, p, libc.Int32FromUint16((*(*struct {
					FiOrderByCol Tu16
					FiAlias      Tu16
				})(unsafe.Pointer(pItem + 16))).FiOrderByCol)-int32(1))
				if pColl == uintptr(0) {
					pColl = (*Tsqlite3)(unsafe.Pointer(db)).FpDfltColl
				}
				(*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(i)*20))).FpExpr = _sqlite3ExprAddCollateString(tls, pParse, pTerm, (*TCollSeq)(unsafe.Pointer(pColl)).FzName)
			}
			*(*uintptr)(unsafe.Pointer(pRet + 20 + uintptr(i)*4)) = pColl
			**(**Tu8)(__ccgo_up((*TKeyInfo)(unsafe.Pointer(pRet)).FaSortFlags + uintptr(i))) = (*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(i)*20))).Ffg.FsortFlags
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	return pRet
}

// C documentation
//
//	/*
//	** If pBt points to an empty file then convert that empty file
//	** into a new empty database by initializing the first page of
//	** the database.
//	*/
func _newDatabase(tls *libc.TLS, pBt uintptr) (r int32) {
	var data, pP1, v1 uintptr
	var rc int32
	_, _, _, _ = data, pP1, rc, v1
	if (*TBtShared)(unsafe.Pointer(pBt)).FnPage > uint32(0) {
		return SQLITE_OK
	}
	pP1 = (*TBtShared)(unsafe.Pointer(pBt)).FpPage1
	data = (*TMemPage)(unsafe.Pointer(pP1)).FaData
	rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pP1)).FpDbPage)
	if rc != 0 {
		return rc
	}
	libc.Xmemcpy(tls, data, uintptr(unsafe.Pointer(&_zMagicHeader)), uint32(16))
	**(**uint8)(__ccgo_up(data + 16)) = uint8((*TBtShared)(unsafe.Pointer(pBt)).FpageSize >> libc.Int32FromInt32(8) & libc.Uint32FromInt32(0xff))
	**(**uint8)(__ccgo_up(data + 17)) = uint8((*TBtShared)(unsafe.Pointer(pBt)).FpageSize >> libc.Int32FromInt32(16) & libc.Uint32FromInt32(0xff))
	**(**uint8)(__ccgo_up(data + 18)) = uint8(1)
	**(**uint8)(__ccgo_up(data + 19)) = uint8(1)
	**(**uint8)(__ccgo_up(data + 20)) = uint8((*TBtShared)(unsafe.Pointer(pBt)).FpageSize - (*TBtShared)(unsafe.Pointer(pBt)).FusableSize)
	**(**uint8)(__ccgo_up(data + 21)) = uint8(64)
	**(**uint8)(__ccgo_up(data + 22)) = uint8(32)
	**(**uint8)(__ccgo_up(data + 23)) = uint8(32)
	libc.Xmemset(tls, data+24, 0, libc.Uint32FromInt32(libc.Int32FromInt32(100)-libc.Int32FromInt32(24)))
	_zeroPage(tls, pP1, libc.Int32FromInt32(PTF_INTKEY)|libc.Int32FromInt32(PTF_LEAF)|libc.Int32FromInt32(PTF_LEAFDATA))
	v1 = pBt + 24
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTS_PAGESIZE_FIXED))
	_sqlite3Put4byte(tls, data+uintptr(libc.Int32FromInt32(36)+libc.Int32FromInt32(4)*libc.Int32FromInt32(4)), uint32((*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum))
	_sqlite3Put4byte(tls, data+uintptr(libc.Int32FromInt32(36)+libc.Int32FromInt32(7)*libc.Int32FromInt32(4)), uint32((*TBtShared)(unsafe.Pointer(pBt)).FincrVacuum))
	(*TBtShared)(unsafe.Pointer(pBt)).FnPage = uint32(1)
	**(**uint8)(__ccgo_up(data + 31)) = uint8(1)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Remove the cell with index iCell from node pNode.
//	*/
func _nodeDeleteCell(tls *libc.TLS, pRtree uintptr, pNode uintptr, iCell int32) {
	var nByte int32
	var pDst, pSrc uintptr
	_, _, _ = nByte, pDst, pSrc
	pDst = (*TRtreeNode)(unsafe.Pointer(pNode)).FzData + uintptr(int32(4)+libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell)*iCell)
	pSrc = pDst + uintptr((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell)
	nByte = (_readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData+2) - iCell - int32(1)) * libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell)
	libc.Xmemmove(tls, pDst, pSrc, libc.Uint32FromInt32(nByte))
	_writeInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData+2, _readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData+2)-int32(1))
	(*TRtreeNode)(unsafe.Pointer(pNode)).FisDirty = int32(1)
}

// C documentation
//
//	/*
//	** Clear the content of node p (set all bytes to 0x00).
//	*/
func _nodeZero(tls *libc.TLS, pRtree uintptr, p uintptr) {
	libc.Xmemset(tls, (*TRtreeNode)(unsafe.Pointer(p)).FzData+2, 0, libc.Uint32FromInt32((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize-int32(2)))
	(*TRtreeNode)(unsafe.Pointer(p)).FisDirty = int32(1)
}

// C documentation
//
//	/*
//	** An index on expressions is being used in the inner loop of an
//	** aggregate query with a GROUP BY clause.  This routine attempts
//	** to adjust the AggInfo object to take advantage of index and to
//	** perhaps use the index as a covering index.
//	**
//	*/
func _optimizeAggregateUseOfIndexedExpr(tls *libc.TLS, pParse uintptr, pSelect uintptr, pAggInfo uintptr, pNC uintptr) {
	var j, k, mx int32
	_, _, _ = j, k, mx
	(*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn = (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnAccumulator
	if (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnSortingColumn > uint32(0) {
		mx = (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSelect)).FpGroupBy)).FnExpr - int32(1)
		j = 0
		for {
			if !(j < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn) {
				break
			}
			k = (**(**TAggInfo_col)(__ccgo_up((*TAggInfo)(unsafe.Pointer(pAggInfo)).FaCol + uintptr(j)*20))).FiSorterColumn
			if k > mx {
				mx = k
			}
			goto _1
		_1:
			;
			j = j + 1
		}
		(*TAggInfo)(unsafe.Pointer(pAggInfo)).FnSortingColumn = libc.Uint32FromInt32(mx + int32(1))
	}
	_analyzeAggFuncArgs(tls, pAggInfo, pNC)
	_ = pSelect
	_ = pParse
}

func _out2Prerelease(tls *libc.TLS, p uintptr, pOp uintptr) (r uintptr) {
	var pOut uintptr
	_ = pOut
	pOut = (*TVdbe)(unsafe.Pointer(p)).FaMem + uintptr((*TVdbeOp)(unsafe.Pointer(pOp)).Fp2)*40
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pOut)).Fflags)&(libc.Int32FromInt32(MEM_Agg)|libc.Int32FromInt32(MEM_Dyn)) != 0 { /*OPTIMIZATION-IF-FALSE*/
		return _out2PrereleaseWithClear(tls, pOut)
	} else {
		(*TMem)(unsafe.Pointer(pOut)).Fflags = uint16(MEM_Int)
		return pOut
	}
	return r
}

// C documentation
//
//	/*
//	** Search the free-list on page pPg for space to store a cell nByte bytes in
//	** size. If one can be found, return a pointer to the space and remove it
//	** from the free-list.
//	**
//	** If no suitable space can be found on the free-list, return NULL.
//	**
//	** This function may detect corruption within pPg.  If corruption is
//	** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
//	**
//	** Slots on the free list that are between 1 and 3 bytes larger than nByte
//	** will be ignored if adding the extra space to the fragmentation count
//	** causes the fragmentation count to exceed 60.
//	*/
func _pageFindSlot(tls *libc.TLS, pPg uintptr, nByte int32, pRc uintptr) (r uintptr) {
	var aData, pTmp, v2 uintptr
	var hdr, iAddr, maxPC, pc, size, x, v1 int32
	_, _, _, _, _, _, _, _, _, _ = aData, hdr, iAddr, maxPC, pTmp, pc, size, x, v1, v2
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FhdrOffset)                                                                      /* Offset to page header */
	aData = (*TMemPage)(unsafe.Pointer(pPg)).FaData                                                                                             /* Page data */
	iAddr = hdr + int32(1)                                                                                                                      /* Address of ptr to pc */
	pTmp = aData + uintptr(iAddr)                                                                                                               /* Temporary ptr into aData[] */
	pc = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp + 1)))                        /* Excess size of the slot */
	maxPC = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPg)).FpBt)).FusableSize - libc.Uint32FromInt32(nByte)) /* Size of the free slot */
	for pc <= maxPC {
		/* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
		 ** freeblock form a big-endian integer which is the size of the freeblock
		 ** in bytes, including the 4-byte header. */
		pTmp = aData + uintptr(pc+int32(2))
		size = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp + 1)))
		v1 = size - nByte
		x = v1
		if v1 >= 0 {
			if x < int32(4) {
				/* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
				 ** number of bytes in fragments may not exceed 60. */
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(7))))) > int32(57) {
					return uintptr(0)
				}
				/* Remove the slot from the free-list. Update the number of
				 ** fragmented bytes within the page. */
				libc.Xmemcpy(tls, aData+uintptr(iAddr), aData+uintptr(pc), uint32(2))
				v2 = aData + uintptr(hdr+int32(7))
				*(*Tu8)(unsafe.Pointer(v2)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v2))) + libc.Int32FromUint8(libc.Uint8FromInt32(x)))
				return aData + uintptr(pc)
			} else {
				if x+pc > maxPC {
					/* This slot extends off the end of the usable part of the page */
					**(**int32)(__ccgo_up(pRc)) = _sqlite3CorruptError(tls, int32(75005))
					return uintptr(0)
				} else {
					/* The slot remains on the free-list. Reduce its size to account
					 ** for the portion used by the new allocation. */
					**(**Tu8)(__ccgo_up(aData + uintptr(pc+int32(2)))) = libc.Uint8FromInt32(x >> libc.Int32FromInt32(8))
					**(**Tu8)(__ccgo_up(aData + uintptr(pc+int32(2)) + 1)) = libc.Uint8FromInt32(x)
				}
			}
			return aData + uintptr(pc+x)
		}
		iAddr = pc
		pTmp = aData + uintptr(pc)
		pc = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTmp + 1)))
		if pc <= iAddr {
			if pc != 0 {
				/* The next slot in the chain comes before the current slot */
				**(**int32)(__ccgo_up(pRc)) = _sqlite3CorruptError(tls, int32(75020))
			}
			return uintptr(0)
		}
	}
	if pc > maxPC+nByte-int32(4) {
		/* The free slot chain extends off the end of the page */
		**(**int32)(__ccgo_up(pRc)) = _sqlite3CorruptError(tls, int32(75027))
	}
	return uintptr(0)
}

// C documentation
//
//	/*
//	** The pCArray object contains pointers to b-tree cells and their sizes.
//	**
//	** This function adds the space associated with each cell in the array
//	** that is currently stored within the body of pPg to the pPg free-list.
//	** The cell-pointers and other fields of the page are not updated.
//	**
//	** This function returns the total number of cells added to the free-list.
//	*/
func _pageFreeArray(tls *libc.TLS, pPg uintptr, iFirst int32, nCell int32, pCArray uintptr) (r int32) {
	var aAfter, aOfst [10]int32
	var aData, pCell, pEnd, pStart uintptr
	var i, iAfter, iEnd, iOfst, j, nFree, nRet, sz int32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _ = aAfter, aData, aOfst, i, iAfter, iEnd, iOfst, j, nFree, nRet, pCell, pEnd, pStart, sz
	aData = (*TMemPage)(unsafe.Pointer(pPg)).FaData
	pEnd = aData + uintptr((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPg)).FpBt)).FusableSize)
	pStart = aData + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FhdrOffset)+int32(8)+libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FchildPtrSize))
	nRet = 0
	iEnd = iFirst + nCell
	nFree = 0
	i = iFirst
	for {
		if !(i < iEnd) {
			break
		}
		pCell = **(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FapCell + uintptr(i)*4))
		if uint32(pCell) >= uint32(pStart) && uint32(pCell) < uint32(pEnd) {
			/* No need to use cachedCellSize() here.  The sizes of all cells that
			 ** are to be freed have already been computing while deciding which
			 ** cells need freeing */
			sz = libc.Int32FromUint16(**(**Tu16)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FszCell + uintptr(i)*2)))
			iOfst = libc.Int32FromUint16(libc.Uint16FromInt32(int32(pCell) - int32(aData)))
			iAfter = iOfst + sz
			j = 0
			for {
				if !(j < nFree) {
					break
				}
				if aOfst[j] == iAfter {
					aOfst[j] = iOfst
					break
				} else {
					if aAfter[j] == iOfst {
						aAfter[j] = iAfter
						break
					}
				}
				goto _2
			_2:
				;
				j = j + 1
			}
			if j >= nFree {
				if nFree >= libc.Int32FromUint32(libc.Uint32FromInt64(40)/libc.Uint32FromInt64(4)) {
					j = 0
					for {
						if !(j < nFree) {
							break
						}
						_freeSpace(tls, pPg, aOfst[j], aAfter[j]-aOfst[j])
						goto _3
					_3:
						;
						j = j + 1
					}
					nFree = 0
				}
				aOfst[nFree] = iOfst
				aAfter[nFree] = iAfter
				if aData+uintptr(iAfter) > pEnd {
					return 0
				}
				nFree = nFree + 1
			}
			nRet = nRet + 1
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	j = 0
	for {
		if !(j < nFree) {
			break
		}
		_freeSpace(tls, pPg, aOfst[j], aAfter[j]-aOfst[j])
		goto _4
	_4:
		;
		j = j + 1
	}
	return nRet
}

// C documentation
//
//	/*
//	** The pCArray objects contains pointers to b-tree cells and the cell sizes.
//	** This function attempts to add the cells stored in the array to page pPg.
//	** If it cannot (because the page needs to be defragmented before the cells
//	** will fit), non-zero is returned. Otherwise, if the cells are added
//	** successfully, zero is returned.
//	**
//	** Argument pCellptr points to the first entry in the cell-pointer array
//	** (part of page pPg) to populate. After cell apCell[0] is written to the
//	** page body, a 16-bit offset is written to pCellptr. And so on, for each
//	** cell in the array. It is the responsibility of the caller to ensure
//	** that it is safe to overwrite this part of the cell-pointer array.
//	**
//	** When this function is called, *ppData points to the start of the
//	** content area on page pPg. If the size of the content area is extended,
//	** *ppData is updated to point to the new start of the content area
//	** before returning.
//	**
//	** Finally, argument pBegin points to the byte immediately following the
//	** end of the space required by this page for the cell-pointer area (for
//	** all cells - not just those inserted by the current call). If the content
//	** area must be extended to before this point in order to accommodate all
//	** cells in apCell[], then the cells do not fit and non-zero is returned.
//	*/
func _pageInsertArray(tls *libc.TLS, pPg uintptr, pBegin uintptr, ppData uintptr, pCellptr uintptr, iFirst int32, nCell int32, pCArray uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aData, pData, pEnd, pSlot, v2 uintptr
	var i, iEnd, k, sz int32
	var v3 bool
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _ = aData, i, iEnd, k, pData, pEnd, pSlot, sz, v2, v3
	i = iFirst                                      /* Loop counter - cell index to insert */
	aData = (*TMemPage)(unsafe.Pointer(pPg)).FaData /* Complete page */
	pData = **(**uintptr)(__ccgo_up(ppData))        /* Content area.  A subset of aData[] */
	iEnd = iFirst + nCell                           /* Maximum extent of cell data */
	/* Never called on page 1 */
	if iEnd <= iFirst {
		return 0
	}
	k = 0
	for {
		if !(**(**int32)(__ccgo_up(pCArray + 40 + uintptr(k)*4)) <= i) {
			break
		}
		goto _1
	_1:
		;
		k = k + 1
	}
	pEnd = **(**uintptr)(__ccgo_up(pCArray + 16 + uintptr(k)*4))
	for int32(1) != 0 {
		sz = libc.Int32FromUint16(**(**Tu16)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FszCell + uintptr(i)*2)))
		if v3 = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + 1))) == 0 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + 2))) == 0; !v3 {
			v2 = _pageFindSlot(tls, pPg, sz, bp)
			pSlot = v2
		}
		if v3 || v2 == uintptr(0) {
			if int32(pData)-int32(pBegin) < sz {
				return int32(1)
			}
			pData = pData - uintptr(sz)
			pSlot = pData
		}
		/* pSlot and pCArray->apCell[i] will never overlap on a well-formed
		 ** database.  But they might for a corrupt database.  Hence use memmove()
		 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
		if uint32(**(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FapCell + uintptr(i)*4))+uintptr(sz)) > uint32(pEnd) && uint32(**(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FapCell + uintptr(i)*4))) < uint32(pEnd) {
			_sqlite3CorruptError(tls, int32(81003))
			return int32(1)
		}
		libc.Xmemmove(tls, pSlot, **(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FapCell + uintptr(i)*4)), libc.Uint32FromInt32(sz))
		**(**Tu8)(__ccgo_up(pCellptr)) = libc.Uint8FromInt32((int32(pSlot) - int32(aData)) >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(pCellptr + 1)) = libc.Uint8FromInt32(int32(pSlot) - int32(aData))
		pCellptr = pCellptr + uintptr(2)
		i = i + 1
		if i >= iEnd {
			break
		}
		if **(**int32)(__ccgo_up(pCArray + 40 + uintptr(k)*4)) <= i {
			k = k + 1
			pEnd = **(**uintptr)(__ccgo_up(pCArray + 16 + uintptr(k)*4))
		}
	}
	**(**uintptr)(__ccgo_up(ppData)) = pData
	return 0
}

// C documentation
//
//	/*
//	** Obtain a reference to a memory mapped page object for page number pgno.
//	** The new object will use the pointer pData, obtained from xFetch().
//	** If successful, set *ppPage to point to the new page reference
//	** and return SQLITE_OK. Otherwise, return an SQLite error code and set
//	** *ppPage to zero.
//	**
//	** Page references obtained by calling this function should be released
//	** by calling pagerReleaseMapPage().
//	*/
func _pagerAcquireMapPage(tls *libc.TLS, pPager uintptr, pgno TPgno, pData uintptr, ppPage uintptr) (r int32) {
	var p, v1 uintptr
	_, _ = p, v1 /* Memory mapped page to return */
	if (*TPager)(unsafe.Pointer(pPager)).FpMmapFreelist != 0 {
		v1 = (*TPager)(unsafe.Pointer(pPager)).FpMmapFreelist
		p = v1
		**(**uintptr)(__ccgo_up(ppPage)) = v1
		(*TPager)(unsafe.Pointer(pPager)).FpMmapFreelist = (*TPgHdr)(unsafe.Pointer(p)).FpDirty
		(*TPgHdr)(unsafe.Pointer(p)).FpDirty = uintptr(0)
		libc.Xmemset(tls, (*TPgHdr)(unsafe.Pointer(p)).FpExtra, 0, uint32(8))
	} else {
		v1 = _sqlite3MallocZero(tls, uint64(uint32(48)+uint32((*TPager)(unsafe.Pointer(pPager)).FnExtra)))
		p = v1
		**(**uintptr)(__ccgo_up(ppPage)) = v1
		if p == uintptr(0) {
			_sqlite3OsUnfetch(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, libc.Int64FromUint32(pgno-libc.Uint32FromInt32(1))*(*TPager)(unsafe.Pointer(pPager)).FpageSize, pData)
			return int32(SQLITE_NOMEM)
		}
		(*TPgHdr)(unsafe.Pointer(p)).FpExtra = p + 1*48
		(*TPgHdr)(unsafe.Pointer(p)).Fflags = uint16(PGHDR_MMAP)
		(*TPgHdr)(unsafe.Pointer(p)).FnRef = int64(1)
		(*TPgHdr)(unsafe.Pointer(p)).FpPager = pPager
	}
	(*TPgHdr)(unsafe.Pointer(p)).Fpgno = pgno
	(*TPgHdr)(unsafe.Pointer(p)).FpData = pData
	(*TPager)(unsafe.Pointer(pPager)).FnMmapOut = (*TPager)(unsafe.Pointer(pPager)).FnMmapOut + 1
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Check that there are at least nSavepoint savepoints open. If there are
//	** currently less than nSavepoints open, then open one or more savepoints
//	** to make up the difference. If the number of savepoints is already
//	** equal to nSavepoint, then this function is a no-op.
//	**
//	** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
//	** occurs while opening the sub-journal file, then an IO error code is
//	** returned. Otherwise, SQLITE_OK.
//	*/
func _pagerOpenSavepoint(tls *libc.TLS, pPager uintptr, nSavepoint int32) (r int32) {
	var aNew uintptr
	var ii, nCurrent, rc int32
	_, _, _, _ = aNew, ii, nCurrent, rc
	rc = SQLITE_OK                                           /* Return code */
	nCurrent = (*TPager)(unsafe.Pointer(pPager)).FnSavepoint /* New Pager.aSavepoint array */
	/* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
	 ** if the allocation fails. Otherwise, zero the new portion in case a
	 ** malloc failure occurs while populating it in the for(...) loop below.
	 */
	aNew = _sqlite3Realloc(tls, (*TPager)(unsafe.Pointer(pPager)).FaSavepoint, uint64(uint32(48)*libc.Uint32FromInt32(nSavepoint)))
	if !(aNew != 0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, aNew+uintptr(nCurrent)*48, 0, libc.Uint32FromInt32(nSavepoint-nCurrent)*uint32(48))
	(*TPager)(unsafe.Pointer(pPager)).FaSavepoint = aNew
	/* Populate the PagerSavepoint structures just allocated. */
	ii = nCurrent
	for {
		if !(ii < nSavepoint) {
			break
		}
		(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FnOrig = (*TPager)(unsafe.Pointer(pPager)).FdbSize
		if (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Fjfd)).FpMethods != uintptr(0) && (*TPager)(unsafe.Pointer(pPager)).FjournalOff > 0 {
			(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FiOffset = (*TPager)(unsafe.Pointer(pPager)).FjournalOff
		} else {
			(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FiOffset = libc.Int64FromUint32((*TPager)(unsafe.Pointer(pPager)).FsectorSize)
		}
		(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FiSubRec = (*TPager)(unsafe.Pointer(pPager)).FnSubRec
		(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FpInSavepoint = _sqlite3BitvecCreate(tls, (*TPager)(unsafe.Pointer(pPager)).FdbSize)
		(**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FbTruncateOnRelease = int32(1)
		if !((**(**TPagerSavepoint)(__ccgo_up(aNew + uintptr(ii)*48))).FpInSavepoint != 0) {
			return int32(SQLITE_NOMEM)
		}
		if (*TPager)(unsafe.Pointer(pPager)).FpWal != uintptr(0) {
			_sqlite3WalSavepoint(tls, (*TPager)(unsafe.Pointer(pPager)).FpWal, aNew+uintptr(ii)*48+32)
		}
		(*TPager)(unsafe.Pointer(pPager)).FnSavepoint = ii + int32(1)
		goto _1
	_1:
		;
		ii = ii + 1
	}
	return rc
}

// C documentation
//
//	/*
//	** This is a variant of sqlite3PagerWrite() that runs when the sector size
//	** is larger than the page size.  SQLite makes the (reasonable) assumption that
//	** all bytes of a sector are written together by hardware.  Hence, all bytes of
//	** a sector need to be journalled in case of a power loss in the middle of
//	** a write.
//	**
//	** Usually, the sector size is less than or equal to the page size, in which
//	** case pages can be individually written.  This routine only runs in the
//	** exceptional case where the page size is smaller than the sector size.
//	*/
func _pagerWriteLargeSector(tls *libc.TLS, pPg uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var ii, nPage, needSync, rc int32
	var nPageCount, nPagePerSector, pg, pg1 TPgno
	var pPage1, pPager, v1 uintptr
	var _ /* pPage at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _ = ii, nPage, nPageCount, nPagePerSector, needSync, pPage1, pPager, pg, pg1, rc, v1
	rc = SQLITE_OK                                  /* First page of the sector pPg is located on. */
	nPage = 0                                       /* Loop counter */
	needSync = 0                                    /* True if any page has PGHDR_NEED_SYNC */
	pPager = (*TPgHdr)(unsafe.Pointer(pPg)).FpPager /* The pager that owns pPg */
	nPagePerSector = libc.Uint32FromInt64(libc.Int64FromUint32((*TPager)(unsafe.Pointer(pPager)).FsectorSize) / (*TPager)(unsafe.Pointer(pPager)).FpageSize)
	/* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
	 ** a journal header to be written between the pages journaled by
	 ** this function.
	 */
	v1 = pPager + 21
	*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(SPILLFLAG_NOSYNC))
	/* This trick assumes that both the page-size and sector-size are
	 ** an integer power of 2. It sets variable pg1 to the identifier
	 ** of the first page of the sector pPg is located on.
	 */
	pg1 = ((*TPgHdr)(unsafe.Pointer(pPg)).Fpgno-uint32(1)) & ^(nPagePerSector-libc.Uint32FromInt32(1)) + uint32(1)
	nPageCount = (*TPager)(unsafe.Pointer(pPager)).FdbSize
	if (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno > nPageCount {
		nPage = libc.Int32FromUint32((*TPgHdr)(unsafe.Pointer(pPg)).Fpgno - pg1 + uint32(1))
	} else {
		if pg1+nPagePerSector-uint32(1) > nPageCount {
			nPage = libc.Int32FromUint32(nPageCount + uint32(1) - pg1)
		} else {
			nPage = libc.Int32FromUint32(nPagePerSector)
		}
	}
	ii = 0
	for {
		if !(ii < nPage && rc == SQLITE_OK) {
			break
		}
		pg = pg1 + libc.Uint32FromInt32(ii)
		if pg == (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno || !(_sqlite3BitvecTest(tls, (*TPager)(unsafe.Pointer(pPager)).FpInJournal, pg) != 0) {
			if pg != (*TPager)(unsafe.Pointer(pPager)).FlckPgno {
				rc = _sqlite3PagerGet(tls, pPager, pg, bp, 0)
				if rc == SQLITE_OK {
					rc = _pager_write(tls, **(**uintptr)(__ccgo_up(bp)))
					if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Fflags)&int32(PGHDR_NEED_SYNC) != 0 {
						needSync = int32(1)
					}
					_sqlite3PagerUnrefNotNull(tls, **(**uintptr)(__ccgo_up(bp)))
				}
			}
		} else {
			v1 = _sqlite3PagerLookup(tls, pPager, pg)
			**(**uintptr)(__ccgo_up(bp)) = v1
			if v1 != uintptr(0) {
				if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Fflags)&int32(PGHDR_NEED_SYNC) != 0 {
					needSync = int32(1)
				}
				_sqlite3PagerUnrefNotNull(tls, **(**uintptr)(__ccgo_up(bp)))
			}
		}
		goto _2
	_2:
		;
		ii = ii + 1
	}
	/* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
	 ** starting at pg1, then it needs to be set for all of them. Because
	 ** writing to any of these nPage pages may damage the others, the
	 ** journal file must contain sync()ed copies of all of them
	 ** before any of them can be written out to the database file.
	 */
	if rc == SQLITE_OK && needSync != 0 {
		ii = 0
		for {
			if !(ii < nPage) {
				break
			}
			pPage1 = _sqlite3PagerLookup(tls, pPager, pg1+libc.Uint32FromInt32(ii))
			if pPage1 != 0 {
				v1 = pPage1 + 28
				*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(PGHDR_NEED_SYNC))
				_sqlite3PagerUnrefNotNull(tls, pPage1)
			}
			goto _4
		_4:
			;
			ii = ii + 1
		}
	}
	v1 = pPager + 21
	*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(SPILLFLAG_NOSYNC))
	return rc
}

// C documentation
//
//	/*
//	** This function is used to change the actual size of the database
//	** file in the file-system. This only happens when committing a transaction,
//	** or rolling back a transaction (including rolling back a hot-journal).
//	**
//	** If the main database file is not open, or the pager is not in either
//	** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
//	** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
//	** If the file on disk is currently larger than nPage pages, then use the VFS
//	** xTruncate() method to truncate it.
//	**
//	** Or, it might be the case that the file on disk is smaller than
//	** nPage pages. Some operating system implementations can get confused if
//	** you try to truncate a file to some size that is larger than it
//	** currently is, so detect this case and write a single zero byte to
//	** the end of the new file instead.
//	**
//	** If successful, return SQLITE_OK. If an IO error occurs while modifying
//	** the database file, return the error code to the caller.
//	*/
func _pager_truncate(tls *libc.TLS, pPager uintptr, nPage TPgno) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pTmp uintptr
	var rc, szPage int32
	var _ /* currentSize at bp+0 */ Ti64
	var _ /* newSize at bp+8 */ Ti64
	_, _, _ = pTmp, rc, szPage
	rc = SQLITE_OK
	if (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Ffd)).FpMethods != uintptr(0) && (libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) >= int32(PAGER_WRITER_DBMOD) || libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) == PAGER_OPEN) {
		szPage = int32((*TPager)(unsafe.Pointer(pPager)).FpageSize)
		/* TODO: Is it safe to use Pager.dbFileSize here? */
		rc = _sqlite3OsFileSize(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, bp)
		**(**Ti64)(__ccgo_up(bp + 8)) = int64(szPage) * libc.Int64FromUint32(nPage)
		if rc == SQLITE_OK && **(**Ti64)(__ccgo_up(bp)) != **(**Ti64)(__ccgo_up(bp + 8)) {
			if **(**Ti64)(__ccgo_up(bp)) > **(**Ti64)(__ccgo_up(bp + 8)) {
				rc = _sqlite3OsTruncate(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, **(**Ti64)(__ccgo_up(bp + 8)))
			} else {
				if **(**Ti64)(__ccgo_up(bp))+int64(szPage) <= **(**Ti64)(__ccgo_up(bp + 8)) {
					pTmp = (*TPager)(unsafe.Pointer(pPager)).FpTmpSpace
					libc.Xmemset(tls, pTmp, 0, libc.Uint32FromInt32(szPage))
					_sqlite3OsFileControlHint(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, int32(SQLITE_FCNTL_SIZE_HINT), bp+8)
					rc = _sqlite3OsWrite(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, pTmp, szPage, **(**Ti64)(__ccgo_up(bp + 8))-int64(szPage))
				}
			}
			if rc == SQLITE_OK {
				(*TPager)(unsafe.Pointer(pPager)).FdbFileSize = nPage
			}
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Mark a single data page as writeable. The page is written into the
//	** main journal or sub-journal as required. If the page is written into
//	** one of the journals, the corresponding bit is set in the
//	** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
//	** of any open savepoints as appropriate.
//	*/
func _pager_write(tls *libc.TLS, pPg uintptr) (r int32) {
	var pPager, v1 uintptr
	var rc int32
	_, _, _ = pPager, rc, v1
	pPager = (*TPgHdr)(unsafe.Pointer(pPg)).FpPager
	rc = SQLITE_OK
	/* This routine is not called unless a write-transaction has already
	 ** been started. The journal file may or may not be open at this point.
	 ** It is never called in the ERROR state.
	 */
	/* The journal file needs to be opened. Higher level routines have already
	 ** obtained the necessary locks to begin the write-transaction, but the
	 ** rollback journal might not yet be open. Open it now if this is the case.
	 **
	 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
	 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
	 ** an error might occur and the pager would end up in WRITER_LOCKED state
	 ** with pages marked as dirty in the cache.
	 */
	if libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) == int32(PAGER_WRITER_LOCKED) {
		rc = _pager_open_journal(tls, pPager)
		if rc != SQLITE_OK {
			return rc
		}
	}
	/* Mark the page that is about to be modified as dirty. */
	_sqlite3PcacheMakeDirty(tls, pPg)
	/* If a rollback journal is in use, them make sure the page that is about
	 ** to change is in the rollback journal, or if the page is a new page off
	 ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
	 */
	if (*TPager)(unsafe.Pointer(pPager)).FpInJournal != uintptr(0) && _sqlite3BitvecTestNotNull(tls, (*TPager)(unsafe.Pointer(pPager)).FpInJournal, (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno) == 0 {
		if (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno <= (*TPager)(unsafe.Pointer(pPager)).FdbOrigSize {
			rc = _pagerAddPageToRollbackJournal(tls, pPg)
			if rc != SQLITE_OK {
				return rc
			}
		} else {
			if libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) != int32(PAGER_WRITER_DBMOD) {
				v1 = pPg + 28
				*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(PGHDR_NEED_SYNC))
			}
		}
	}
	/* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
	 ** and before writing the page into the rollback journal.  Wait until now,
	 ** after the page has been successfully journalled, before setting the
	 ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
	 */
	v1 = pPg + 28
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(PGHDR_WRITEABLE))
	/* If the statement journal is open and the page is not in it,
	 ** then write the page into the statement journal.
	 */
	if (*TPager)(unsafe.Pointer(pPager)).FnSavepoint > 0 {
		rc = _subjournalPageIfRequired(tls, pPg)
	}
	/* Update the database size and return. */
	if (*TPager)(unsafe.Pointer(pPager)).FdbSize < (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno {
		(*TPager)(unsafe.Pointer(pPager)).FdbSize = (*TPgHdr)(unsafe.Pointer(pPg)).Fpgno
	}
	return rc
}

func _parseGrowPhraseArray(tls *libc.TLS, pParse uintptr) (r int32) {
	var apNew uintptr
	var nByte Tsqlite3_int64
	_, _ = apNew, nByte
	if (*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase%int32(8) == 0 {
		nByte = libc.Int64FromUint32(uint32(4) * libc.Uint32FromInt32((*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase+libc.Int32FromInt32(8)))
		apNew = Xsqlite3_realloc64(tls, (*TFts5Parse)(unsafe.Pointer(pParse)).FapPhrase, libc.Uint64FromInt64(nByte))
		if apNew == uintptr(0) {
			(*TFts5Parse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
			return int32(SQLITE_NOMEM)
		}
		(*TFts5Parse)(unsafe.Pointer(pParse)).FapPhrase = apNew
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Malloc function used within this file to allocate space from the buffer
//	** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
//	** such buffer exists or there is no space left in it, this function falls
//	** back to sqlite3Malloc().
//	**
//	** Multiple threads can run this routine at the same time.  Global variables
//	** in pcache1 need to be protected via mutex.
//	*/
func _pcache1Alloc(tls *libc.TLS, nByte int32) (r uintptr) {
	var p uintptr
	var sz int32
	_, _ = p, sz
	p = uintptr(0)
	if nByte <= _pcache1_g.FszSlot {
		Xsqlite3_mutex_enter(tls, _pcache1_g.Fmutex)
		p = _pcache1_g.FpFree
		if p != 0 {
			_pcache1_g.FpFree = (*TPgFreeslot)(unsafe.Pointer(_pcache1_g.FpFree)).FpNext
			_pcache1_g.FnFreeSlot = _pcache1_g.FnFreeSlot - 1
			libc.AtomicStoreNInt32(uintptr(unsafe.Pointer(&_pcache1_g))+96, libc.BoolInt32(_pcache1_g.FnFreeSlot < _pcache1_g.FnReserve), libc.Int32FromInt32(__ATOMIC_RELAXED))
			_sqlite3StatusHighwater(tls, int32(SQLITE_STATUS_PAGECACHE_SIZE), nByte)
			_sqlite3StatusUp(tls, int32(SQLITE_STATUS_PAGECACHE_USED), int32(1))
		}
		Xsqlite3_mutex_leave(tls, _pcache1_g.Fmutex)
	}
	if p == uintptr(0) {
		/* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
		 ** it from sqlite3Malloc instead.
		 */
		p = _sqlite3Malloc(tls, libc.Uint64FromInt32(nByte))
		if p != 0 {
			sz = _sqlite3MallocSize(tls, p)
			Xsqlite3_mutex_enter(tls, _pcache1_g.Fmutex)
			_sqlite3StatusHighwater(tls, int32(SQLITE_STATUS_PAGECACHE_SIZE), nByte)
			_sqlite3StatusUp(tls, int32(SQLITE_STATUS_PAGECACHE_OVERFLOW), sz)
			Xsqlite3_mutex_leave(tls, _pcache1_g.Fmutex)
		}
	}
	return p
}

// C documentation
//
//	/*
//	** Allocate a new page object initially associated with cache pCache.
//	*/
func _pcache1AllocPage(tls *libc.TLS, pCache uintptr, benignMalloc int32) (r uintptr) {
	var p, pPg uintptr
	_, _ = p, pPg
	p = uintptr(0)
	if (*TPCache1)(unsafe.Pointer(pCache)).FpFree != 0 || (*TPCache1)(unsafe.Pointer(pCache)).FnPage == uint32(0) && _pcache1InitBulk(tls, pCache) != 0 {
		p = (*TPCache1)(unsafe.Pointer(pCache)).FpFree
		(*TPCache1)(unsafe.Pointer(pCache)).FpFree = (*TPgHdr1)(unsafe.Pointer(p)).FpNext
		(*TPgHdr1)(unsafe.Pointer(p)).FpNext = uintptr(0)
	} else {
		/* The group mutex must be released before pcache1Alloc() is called. This
		 ** is because it might call sqlite3_release_memory(), which assumes that
		 ** this mutex is not held. */
		Xsqlite3_mutex_leave(tls, (*TPGroup)(unsafe.Pointer((*TPCache1)(unsafe.Pointer(pCache)).FpGroup)).Fmutex)
		if benignMalloc != 0 {
			_sqlite3BeginBenignMalloc(tls)
		}
		pPg = _pcache1Alloc(tls, (*TPCache1)(unsafe.Pointer(pCache)).FszAlloc)
		if benignMalloc != 0 {
			_sqlite3EndBenignMalloc(tls)
		}
		Xsqlite3_mutex_enter(tls, (*TPGroup)(unsafe.Pointer((*TPCache1)(unsafe.Pointer(pCache)).FpGroup)).Fmutex)
		if pPg == uintptr(0) {
			return uintptr(0)
		}
		p = pPg + uintptr((*TPCache1)(unsafe.Pointer(pCache)).FszPage)
		(*TPgHdr1)(unsafe.Pointer(p)).Fpage.FpBuf = pPg
		(*TPgHdr1)(unsafe.Pointer(p)).Fpage.FpExtra = p + uintptr((libc.Uint32FromInt64(32)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
		(*TPgHdr1)(unsafe.Pointer(p)).FisBulkLocal = uint16(0)
		(*TPgHdr1)(unsafe.Pointer(p)).FisAnchor = uint16(0)
		(*TPgHdr1)(unsafe.Pointer(p)).FpLruPrev = uintptr(0) /* Initializing this saves a valgrind error */
	}
	**(**uint32)(__ccgo_up((*TPCache1)(unsafe.Pointer(pCache)).FpnPurgeable)) = **(**uint32)(__ccgo_up((*TPCache1)(unsafe.Pointer(pCache)).FpnPurgeable)) + 1
	return p
}

// C documentation
//
//	/*
//	** Implementation of the sqlite3_pcache.xCachesize method.
//	**
//	** Configure the cache_size limit for a cache.
//	*/
func _pcache1Cachesize(tls *libc.TLS, p uintptr, nMax int32) {
	var n Tu32
	var pCache, pGroup uintptr
	_, _, _ = n, pCache, pGroup
	pCache = p
	if (*TPCache1)(unsafe.Pointer(pCache)).FbPurgeable != 0 {
		pGroup = (*TPCache1)(unsafe.Pointer(pCache)).FpGroup
		Xsqlite3_mutex_enter(tls, (*TPGroup)(unsafe.Pointer(pGroup)).Fmutex)
		n = libc.Uint32FromInt32(nMax)
		if n > uint32(0x7fff0000)-(*TPGroup)(unsafe.Pointer(pGroup)).FnMaxPage+(*TPCache1)(unsafe.Pointer(pCache)).FnMax {
			n = uint32(0x7fff0000) - (*TPGroup)(unsafe.Pointer(pGroup)).FnMaxPage + (*TPCache1)(unsafe.Pointer(pCache)).FnMax
		}
		**(**uint32)(__ccgo_up(pGroup + 4)) += n - (*TPCache1)(unsafe.Pointer(pCache)).FnMax
		(*TPGroup)(unsafe.Pointer(pGroup)).FmxPinned = (*TPGroup)(unsafe.Pointer(pGroup)).FnMaxPage + uint32(10) - (*TPGroup)(unsafe.Pointer(pGroup)).FnMinPage
		(*TPCache1)(unsafe.Pointer(pCache)).FnMax = n
		(*TPCache1)(unsafe.Pointer(pCache)).Fn90pct = (*TPCache1)(unsafe.Pointer(pCache)).FnMax * uint32(9) / uint32(10)
		_pcache1EnforceMaxPage(tls, pCache)
		Xsqlite3_mutex_leave(tls, (*TPGroup)(unsafe.Pointer(pGroup)).Fmutex)
	}
}

// C documentation
//
//	/*
//	** Implementation of the sqlite3_pcache.xCreate method.
//	**
//	** Allocate a new cache.
//	*/
func _pcache1Create(tls *libc.TLS, szPage int32, szExtra int32, bPurgeable int32) (r uintptr) {
	var pCache, pGroup, v1 uintptr
	var sz Ti64
	var v2 int32
	_, _, _, _, _ = pCache, pGroup, sz, v1, v2 /* Bytes of memory required to allocate the new cache */
	sz = libc.Int64FromUint32(uint32(68) + uint32(52)*libc.Uint32FromInt32(_pcache1_g.FseparateCache))
	pCache = _sqlite3MallocZero(tls, libc.Uint64FromInt64(sz))
	if pCache != 0 {
		if _pcache1_g.FseparateCache != 0 {
			pGroup = pCache + 1*68
			(*TPGroup)(unsafe.Pointer(pGroup)).FmxPinned = uint32(10)
		} else {
			pGroup = uintptr(unsafe.Pointer(&_pcache1_g))
		}
		Xsqlite3_mutex_enter(tls, (*TPGroup)(unsafe.Pointer(pGroup)).Fmutex)
		if libc.Int32FromUint16((*TPGroup)(unsafe.Pointer(pGroup)).Flru.FisAnchor) == 0 {
			(*TPGroup)(unsafe.Pointer(pGroup)).Flru.FisAnchor = uint16(1)
			v1 = pGroup + 20
			(*TPGroup)(unsafe.Pointer(pGroup)).Flru.FpLruNext = v1
			(*TPGroup)(unsafe.Pointer(pGroup)).Flru.FpLruPrev = v1
		}
		(*TPCache1)(unsafe.Pointer(pCache)).FpGroup = pGroup
		(*TPCache1)(unsafe.Pointer(pCache)).FszPage = szPage
		(*TPCache1)(unsafe.Pointer(pCache)).FszExtra = szExtra
		(*TPCache1)(unsafe.Pointer(pCache)).FszAlloc = libc.Int32FromUint32(libc.Uint32FromInt32(szPage+szExtra) + (libc.Uint32FromInt64(32)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
		if bPurgeable != 0 {
			v2 = int32(1)
		} else {
			v2 = 0
		}
		(*TPCache1)(unsafe.Pointer(pCache)).FbPurgeable = v2
		_pcache1ResizeHash(tls, pCache)
		if bPurgeable != 0 {
			(*TPCache1)(unsafe.Pointer(pCache)).FnMin = uint32(10)
			**(**uint32)(__ccgo_up(pGroup + 8)) += (*TPCache1)(unsafe.Pointer(pCache)).FnMin
			(*TPGroup)(unsafe.Pointer(pGroup)).FmxPinned = (*TPGroup)(unsafe.Pointer(pGroup)).FnMaxPage + uint32(10) - (*TPGroup)(unsafe.Pointer(pGroup)).FnMinPage
			(*TPCache1)(unsafe.Pointer(pCache)).FpnPurgeable = pGroup + 16
		} else {
			(*TPCache1)(unsafe.Pointer(pCache)).FpnPurgeable = pCache + 40
		}
		Xsqlite3_mutex_leave(tls, (*TPGroup)(unsafe.Pointer(pGroup)).Fmutex)
		if (*TPCache1)(unsafe.Pointer(pCache)).FnHash == uint32(0) {
			_pcache1Destroy(tls, pCache)
			pCache = uintptr(0)
		}
	}
	return pCache
}

// C documentation
//
//	/*
//	** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
//	** in the header of the pcache1Fetch() procedure.
//	**
//	** This steps are broken out into a separate procedure because they are
//	** usually not needed, and by avoiding the stack initialization required
//	** for these steps, the main pcache1Fetch() procedure can run faster.
//	*/
func _pcache1FetchStage2(tls *libc.TLS, pCache uintptr, iKey uint32, createFlag int32) (r uintptr) {
	var h, nPinned uint32
	var pGroup, pOther, pPage uintptr
	_, _, _, _, _ = h, nPinned, pGroup, pOther, pPage
	pGroup = (*TPCache1)(unsafe.Pointer(pCache)).FpGroup
	pPage = uintptr(0)
	/* Step 3: Abort if createFlag is 1 but the cache is nearly full */
	nPinned = (*TPCache1)(unsafe.Pointer(pCache)).FnPage - (*TPCache1)(unsafe.Pointer(pCache)).FnRecyclable
	if createFlag == int32(1) && (nPinned >= (*TPGroup)(unsafe.Pointer(pGroup)).FmxPinned || nPinned >= (*TPCache1)(unsafe.Pointer(pCache)).Fn90pct || _pcache1UnderMemoryPressure(tls, pCache) != 0 && (*TPCache1)(unsafe.Pointer(pCache)).FnRecyclable < nPinned) {
		return uintptr(0)
	}
	if (*TPCache1)(unsafe.Pointer(pCache)).FnPage >= (*TPCache1)(unsafe.Pointer(pCache)).FnHash {
		_pcache1ResizeHash(tls, pCache)
	}
	/* Step 4. Try to recycle a page. */
	if (*TPCache1)(unsafe.Pointer(pCache)).FbPurgeable != 0 && !((*TPgHdr1)(unsafe.Pointer((*TPGroup)(unsafe.Pointer(pGroup)).Flru.FpLruPrev)).FisAnchor != 0) && ((*TPCache1)(unsafe.Pointer(pCache)).FnPage+uint32(1) >= (*TPCache1)(unsafe.Pointer(pCache)).FnMax || _pcache1UnderMemoryPressure(tls, pCache) != 0) {
		pPage = (*TPGroup)(unsafe.Pointer(pGroup)).Flru.FpLruPrev
		_pcache1RemoveFromHash(tls, pPage, 0)
		_pcache1PinPage(tls, pPage)
		pOther = (*TPgHdr1)(unsafe.Pointer(pPage)).FpCache
		if (*TPCache1)(unsafe.Pointer(pOther)).FszAlloc != (*TPCache1)(unsafe.Pointer(pCache)).FszAlloc {
			_pcache1FreePage(tls, pPage)
			pPage = uintptr(0)
		} else {
			**(**uint32)(__ccgo_up(pGroup + 16)) -= libc.Uint32FromInt32((*TPCache1)(unsafe.Pointer(pOther)).FbPurgeable - (*TPCache1)(unsafe.Pointer(pCache)).FbPurgeable)
		}
	}
	/* Step 5. If a usable page buffer has still not been found,
	 ** attempt to allocate a new one.
	 */
	if !(pPage != 0) {
		pPage = _pcache1AllocPage(tls, pCache, libc.BoolInt32(createFlag == int32(1)))
	}
	if pPage != 0 {
		h = iKey % (*TPCache1)(unsafe.Pointer(pCache)).FnHash
		(*TPCache1)(unsafe.Pointer(pCache)).FnPage = (*TPCache1)(unsafe.Pointer(pCache)).FnPage + 1
		(*TPgHdr1)(unsafe.Pointer(pPage)).FiKey = iKey
		(*TPgHdr1)(unsafe.Pointer(pPage)).FpNext = **(**uintptr)(__ccgo_up((*TPCache1)(unsafe.Pointer(pCache)).FapHash + uintptr(h)*4))
		(*TPgHdr1)(unsafe.Pointer(pPage)).FpCache = pCache
		(*TPgHdr1)(unsafe.Pointer(pPage)).FpLruNext = uintptr(0)
		/* pPage->pLruPrev = 0;
		 ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
		**(**uintptr)(__ccgo_up((*TPgHdr1)(unsafe.Pointer(pPage)).Fpage.FpExtra)) = uintptr(0)
		**(**uintptr)(__ccgo_up((*TPCache1)(unsafe.Pointer(pCache)).FapHash + uintptr(h)*4)) = pPage
		if iKey > (*TPCache1)(unsafe.Pointer(pCache)).FiMaxKey {
			(*TPCache1)(unsafe.Pointer(pCache)).FiMaxKey = iKey
		}
	}
	return pPage
}

// C documentation
//
//	/*
//	** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
//	** true if pCache->pFree ends up containing one or more free pages.
//	*/
func _pcache1InitBulk(tls *libc.TLS, pCache uintptr) (r int32) {
	var nBulk, v2 int32
	var pX, zBulk, v1 uintptr
	var szBulk Ti64
	_, _, _, _, _, _ = nBulk, pX, szBulk, zBulk, v1, v2
	if _pcache1_g.FnInitPage == 0 {
		return 0
	}
	/* Do not bother with a bulk allocation if the cache size very small */
	if (*TPCache1)(unsafe.Pointer(pCache)).FnMax < uint32(3) {
		return 0
	}
	_sqlite3BeginBenignMalloc(tls)
	if _pcache1_g.FnInitPage > 0 {
		szBulk = int64((*TPCache1)(unsafe.Pointer(pCache)).FszAlloc) * int64(_pcache1_g.FnInitPage)
	} else {
		szBulk = int64(-int32(1024)) * int64(_pcache1_g.FnInitPage)
	}
	if szBulk > int64((*TPCache1)(unsafe.Pointer(pCache)).FszAlloc)*libc.Int64FromUint32((*TPCache1)(unsafe.Pointer(pCache)).FnMax) {
		szBulk = int64((*TPCache1)(unsafe.Pointer(pCache)).FszAlloc) * libc.Int64FromUint32((*TPCache1)(unsafe.Pointer(pCache)).FnMax)
	}
	if szBulk >= int64((*TPCache1)(unsafe.Pointer(pCache)).FszAlloc) {
		v1 = _sqlite3Malloc(tls, libc.Uint64FromInt64(szBulk))
		(*TPCache1)(unsafe.Pointer(pCache)).FpBulk = v1
		zBulk = v1
		_sqlite3EndBenignMalloc(tls)
		if zBulk != 0 {
			nBulk = _sqlite3MallocSize(tls, zBulk) / (*TPCache1)(unsafe.Pointer(pCache)).FszAlloc
			for {
				pX = zBulk + uintptr((*TPCache1)(unsafe.Pointer(pCache)).FszPage)
				(*TPgHdr1)(unsafe.Pointer(pX)).Fpage.FpBuf = zBulk
				(*TPgHdr1)(unsafe.Pointer(pX)).Fpage.FpExtra = pX + uintptr((libc.Uint32FromInt64(32)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
				(*TPgHdr1)(unsafe.Pointer(pX)).FisBulkLocal = uint16(1)
				(*TPgHdr1)(unsafe.Pointer(pX)).FisAnchor = uint16(0)
				(*TPgHdr1)(unsafe.Pointer(pX)).FpNext = (*TPCache1)(unsafe.Pointer(pCache)).FpFree
				(*TPgHdr1)(unsafe.Pointer(pX)).FpLruPrev = uintptr(0) /* Initializing this saves a valgrind error */
				(*TPCache1)(unsafe.Pointer(pCache)).FpFree = pX
				zBulk = zBulk + uintptr((*TPCache1)(unsafe.Pointer(pCache)).FszAlloc)
				goto _3
			_3:
				;
				nBulk = nBulk - 1
				v2 = nBulk
				if !(v2 != 0) {
					break
				}
			}
		}
	}
	return libc.BoolInt32((*TPCache1)(unsafe.Pointer(pCache)).FpFree != uintptr(0))
}

// C documentation
//
//	/*
//	** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
//	** computed.
//	*/
func _populateCellCache(tls *libc.TLS, p uintptr, idx int32, N int32) {
	var pRef, szCell uintptr
	_, _ = pRef, szCell
	pRef = (*TCellArray)(unsafe.Pointer(p)).FpRef
	szCell = (*TCellArray)(unsafe.Pointer(p)).FszCell
	for N > 0 {
		if libc.Int32FromUint16(**(**Tu16)(__ccgo_up(szCell + uintptr(idx)*2))) == 0 {
			**(**Tu16)(__ccgo_up(szCell + uintptr(idx)*2)) = (*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pRef)).FxCellSize})))(tls, pRef, **(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(p)).FapCell + uintptr(idx)*4)))
		} else {
		}
		idx = idx + 1
		N = N - 1
	}
}

// C documentation
//
//	/*
//	** Locate a pragma in the aPragmaName[] array.
//	*/
func _pragmaLocate(tls *libc.TLS, zName uintptr) (r uintptr) {
	var lwr, mid, rc, upr int32
	var v1 uintptr
	_, _, _, _, _ = lwr, mid, rc, upr, v1
	mid = 0
	lwr = 0
	upr = libc.Int32FromUint32(libc.Uint32FromInt64(1056)/libc.Uint32FromInt64(16)) - libc.Int32FromInt32(1)
	for lwr <= upr {
		mid = (lwr + upr) / int32(2)
		rc = Xsqlite3_stricmp(tls, zName, _aPragmaName[mid].FzName)
		if rc == 0 {
			break
		}
		if rc < 0 {
			upr = mid - int32(1)
		} else {
			lwr = mid + int32(1)
		}
	}
	if lwr > upr {
		v1 = uintptr(0)
	} else {
		v1 = uintptr(unsafe.Pointer(&_aPragmaName)) + uintptr(mid)*16
	}
	return v1
}

// C documentation
//
//	/* The xColumn method simply returns the corresponding column from
//	** the PRAGMA.
//	*/
func _pragmaVtabColumn(tls *libc.TLS, pVtabCursor uintptr, ctx uintptr, i int32) (r int32) {
	var pCsr, pTab uintptr
	_, _ = pCsr, pTab
	pCsr = pVtabCursor
	pTab = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(pVtabCursor)).FpVtab
	if i < libc.Int32FromUint8((*TPragmaVtab)(unsafe.Pointer(pTab)).FiHidden) {
		Xsqlite3_result_value(tls, ctx, Xsqlite3_column_value(tls, (*TPragmaVtabCursor)(unsafe.Pointer(pCsr)).FpPragma, i))
	} else {
		Xsqlite3_result_text(tls, ctx, **(**uintptr)(__ccgo_up(pCsr + 16 + uintptr(i-libc.Int32FromUint8((*TPragmaVtab)(unsafe.Pointer(pTab)).FiHidden))*4)), -int32(1), uintptr(-libc.Int32FromInt32(1)))
	}
	return SQLITE_OK
}

// C documentation
//
//	/* Clear all content from pragma virtual table cursor. */
func _pragmaVtabCursorClear(tls *libc.TLS, pCsr uintptr) {
	var i int32
	_ = i
	Xsqlite3_finalize(tls, (*TPragmaVtabCursor)(unsafe.Pointer(pCsr)).FpPragma)
	(*TPragmaVtabCursor)(unsafe.Pointer(pCsr)).FpPragma = uintptr(0)
	(*TPragmaVtabCursor)(unsafe.Pointer(pCsr)).FiRowid = 0
	i = 0
	for {
		if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(8)/libc.Uint32FromInt64(4))) {
			break
		}
		Xsqlite3_free(tls, **(**uintptr)(__ccgo_up(pCsr + 16 + uintptr(i)*4)))
		**(**uintptr)(__ccgo_up(pCsr + 16 + uintptr(i)*4)) = uintptr(0)
		goto _1
	_1:
		;
		i = i + 1
	}
}

// C documentation
//
//	/*
//	** fts5VisitEntries() callback used by fts5SetupPrefixIter()
//	*/
func _prefixIterSetupCb(tls *libc.TLS, p uintptr, pCtx uintptr, p1 uintptr, pNew uintptr, nNew int32) {
	var i, i1, iStore, nMerge int32
	var pSetup uintptr
	_, _, _, _, _ = i, i1, iStore, nMerge, pSetup
	pSetup = pCtx
	nMerge = (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FnMerge
	if (*TFts5Iter)(unsafe.Pointer(p1)).Fbase.FnData > 0 {
		if (*TFts5Iter)(unsafe.Pointer(p1)).Fbase.FiRowid <= (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FiLastRowid && (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).Fdoclist.Fn > 0 {
			i = 0
			for {
				if !((*TFts5Index)(unsafe.Pointer(p)).Frc == SQLITE_OK && (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).Fdoclist.Fn != 0) {
					break
				}
				i1 = i * nMerge
				iStore = i1
				for {
					if !(iStore < i1+nMerge) {
						break
					}
					if (**(**TFts5Buffer)(__ccgo_up((*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FaBuf + uintptr(iStore)*12))).Fn == 0 {
						_fts5BufferSwap(tls, pSetup+28, (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FaBuf+uintptr(iStore)*12)
						_sqlite3Fts5BufferZero(tls, pSetup+28)
						break
					}
					goto _2
				_2:
					;
					iStore = iStore + 1
				}
				if iStore == i1+nMerge {
					(*(*func(*libc.TLS, uintptr, uintptr, int32, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FxMerge})))(tls, p, pSetup+28, nMerge, (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FaBuf+uintptr(i1)*12)
					iStore = i1
					for {
						if !(iStore < i1+nMerge) {
							break
						}
						_sqlite3Fts5BufferZero(tls, (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FaBuf+uintptr(iStore)*12)
						goto _3
					_3:
						;
						iStore = iStore + 1
					}
				}
				goto _1
			_1:
				;
				i = i + 1
			}
			(*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FiLastRowid = 0
		}
		(*(*func(*libc.TLS, uintptr, Tu64, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FxAppend})))(tls, p, libc.Uint64FromInt64((*TFts5Iter)(unsafe.Pointer(p1)).Fbase.FiRowid)-libc.Uint64FromInt64((*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FiLastRowid), p1, pSetup+28)
		(*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FiLastRowid = (*TFts5Iter)(unsafe.Pointer(p1)).Fbase.FiRowid
	}
	if (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FpTokendata != 0 {
		_prefixIterSetupTokendataCb(tls, p, (*TPrefixSetupCtx)(unsafe.Pointer(pSetup)).FpTokendata, p1, pNew, nNew)
	}
}

// C documentation
//
//	/*
//	** The cell pCell is currently part of page pSrc but will ultimately be part
//	** of pPage.  (pSrc and pPage are often the same.)  If pCell contains a
//	** pointer to an overflow page, insert an entry into the pointer-map for
//	** the overflow page that will be valid after pCell has been moved to pPage.
//	*/
func _ptrmapPutOvflPtr(tls *libc.TLS, pPage uintptr, pSrc uintptr, pCell uintptr, pRC uintptr) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var ovfl TPgno
	var _ /* info at bp+0 */ TCellInfo
	_ = ovfl
	if **(**int32)(__ccgo_up(pRC)) != 0 {
		return
	}
	(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxParseCell})))(tls, pPage, pCell, bp)
	if uint32((**(**TCellInfo)(__ccgo_up(bp))).FnLocal) < (**(**TCellInfo)(__ccgo_up(bp))).FnPayload {
		if uint32(pCell) < uint32((*TMemPage)(unsafe.Pointer(pSrc)).FaDataEnd) && uint32(pCell+uintptr((**(**TCellInfo)(__ccgo_up(bp))).FnLocal)) > uint32((*TMemPage)(unsafe.Pointer(pSrc)).FaDataEnd) {
			**(**int32)(__ccgo_up(pRC)) = _sqlite3CorruptError(tls, int32(74817))
			return
		}
		ovfl = _sqlite3Get4byte(tls, pCell+uintptr(libc.Int32FromUint16((**(**TCellInfo)(__ccgo_up(bp))).FnSize)-int32(4)))
		_ptrmapPut(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpBt, ovfl, uint8(PTRMAP_OVERFLOW1), (*TMemPage)(unsafe.Pointer(pPage)).Fpgno, pRC)
	}
}

// C documentation
//
//	/*
//	** Make copies of relevant WHERE clause terms of the outer query into
//	** the WHERE clause of subquery.  Example:
//	**
//	**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
//	**
//	** Transformed into:
//	**
//	**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
//	**     WHERE x=5 AND y=10;
//	**
//	** The hope is that the terms added to the inner query will make it more
//	** efficient.
//	**
//	** NAME AMBIGUITY
//	**
//	** This optimization is called the "WHERE-clause push-down optimization"
//	** or sometimes the "predicate push-down optimization".
//	**
//	** Do not confuse this optimization with another unrelated optimization
//	** with a similar name:  The "MySQL push-down optimization" causes WHERE
//	** clause terms that can be evaluated using only the index and without
//	** reference to the table are run first, so that if they are false,
//	** unnecessary table seeks are avoided.
//	**
//	** RULES
//	**
//	** Do not attempt this optimization if:
//	**
//	**   (1) (** This restriction was removed on 2017-09-29.  We used to
//	**           disallow this optimization for aggregate subqueries, but now
//	**           it is allowed by putting the extra terms on the HAVING clause.
//	**           The added HAVING clause is pointless if the subquery lacks
//	**           a GROUP BY clause.  But such a HAVING clause is also harmless
//	**           so there does not appear to be any reason to add extra logic
//	**           to suppress it. **)
//	**
//	**   (2) The inner query is the recursive part of a common table expression.
//	**
//	**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
//	**       clause would change the meaning of the LIMIT).
//	**
//	**   (4) The inner query is the right operand of a LEFT JOIN and the
//	**       expression to be pushed down does not come from the ON clause
//	**       on that LEFT JOIN.
//	**
//	**   (5) The WHERE clause expression originates in the ON or USING clause
//	**       of a LEFT JOIN where iCursor is not the right-hand table of that
//	**       left join.  An example:
//	**
//	**           SELECT *
//	**           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
//	**           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
//	**           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
//	**
//	**       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).
//	**       But if the (b2=2) term were to be pushed down into the bb subquery,
//	**       then the (1,1,NULL) row would be suppressed.
//	**
//	**   (6) Window functions make things tricky as changes to the WHERE clause
//	**       of the inner query could change the window over which window
//	**       functions are calculated. Therefore, do not attempt the optimization
//	**       if:
//	**
//	**     (6a) The inner query uses multiple incompatible window partitions.
//	**
//	**     (6b) The inner query is a compound and uses window-functions.
//	**
//	**     (6c) The WHERE clause does not consist entirely of constants and
//	**          copies of expressions found in the PARTITION BY clause of
//	**          all window-functions used by the sub-query. It is safe to
//	**          filter out entire partitions, as this does not change the
//	**          window over which any window-function is calculated.
//	**
//	**   (7) The inner query is a Common Table Expression (CTE) that should
//	**       be materialized.  (This restriction is implemented in the calling
//	**       routine.)
//	**
//	**   (8) If the subquery is a compound that uses UNION, INTERSECT,
//	**       or EXCEPT, then all of the result set columns for all arms of
//	**       the compound must use the BINARY collating sequence.
//	**
//	**   (9) All three of the following are true:
//	**
//	**       (9a) The WHERE clause expression originates in the ON or USING clause
//	**            of a join (either an INNER or an OUTER join), and
//	**
//	**       (9b) The subquery is to the right of the ON/USING clause
//	**
//	**       (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
//	**            clause and the subquery.
//	**
//	**       Without this restriction, the WHERE-clause push-down optimization
//	**       might move the ON/USING filter expression from the left side of a
//	**       RIGHT JOIN over to the right side, which leads to incorrect answers.
//	**       See also restriction (6) in sqlite3ExprIsSingleTableConstraint().
//	**
//	**  (10) The inner query is not the right-hand table of a RIGHT JOIN.
//	**
//	**  (11) The subquery is not a VALUES clause
//	**
//	**  (12) The WHERE clause is not "rowid ISNULL" or the equivalent.  This
//	**       case only comes up if SQLite is compiled using
//	**       SQLITE_ALLOW_ROWID_IN_VIEW.
//	**
//	** Return 0 if no changes are made and non-zero if one or more WHERE clause
//	** terms are duplicated into the subquery.
//	*/
func _pushDownWhereTerms(tls *libc.TLS, pParse uintptr, pSubq uintptr, pWhere uintptr, pSrcList uintptr, iSrc int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var ii, nChng, notUnionAll int32
	var op Tu8
	var pColl, pList, pNew, pSel, pSrc uintptr
	var _ /* x at bp+0 */ TSubstContext
	_, _, _, _, _, _, _, _, _ = ii, nChng, notUnionAll, op, pColl, pList, pNew, pSel, pSrc /* The subquery FROM term into which WHERE is pushed */
	nChng = 0
	pSrc = pSrcList + 8 + uintptr(iSrc)*48
	if pWhere == uintptr(0) {
		return 0
	}
	if (*TSelect)(unsafe.Pointer(pSubq)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Recursive)|libc.Int32FromInt32(SF_MultiPart)) != 0 {
		return 0 /* restrictions (2) and (11) */
	}
	if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSrc)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_LTORJ)|libc.Int32FromInt32(JT_RIGHT)) != 0 {
		return 0 /* restrictions (10) */
	}
	if (*TSelect)(unsafe.Pointer(pSubq)).FpPrior != 0 {
		notUnionAll = 0
		pSel = pSubq
		for {
			if !(pSel != 0) {
				break
			}
			op = (*TSelect)(unsafe.Pointer(pSel)).Fop
			if libc.Int32FromUint8(op) != int32(TK_ALL) && libc.Int32FromUint8(op) != int32(TK_SELECT) {
				notUnionAll = int32(1)
			}
			if (*TSelect)(unsafe.Pointer(pSel)).FpWin != 0 {
				return 0
			} /* restriction (6b) */
			goto _1
		_1:
			;
			pSel = (*TSelect)(unsafe.Pointer(pSel)).FpPrior
		}
		if notUnionAll != 0 {
			/* If any of the compound arms are connected using UNION, INTERSECT,
			 ** or EXCEPT, then we must ensure that none of the columns use a
			 ** non-BINARY collating sequence. */
			pSel = pSubq
			for {
				if !(pSel != 0) {
					break
				}
				pList = (*TSelect)(unsafe.Pointer(pSel)).FpEList
				ii = 0
				for {
					if !(ii < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
						break
					}
					pColl = _sqlite3ExprCollSeq(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(ii)*20))).FpExpr)
					if !(_sqlite3IsBinary(tls, pColl) != 0) {
						return 0 /* Restriction (8) */
					}
					goto _3
				_3:
					;
					ii = ii + 1
				}
				goto _2
			_2:
				;
				pSel = (*TSelect)(unsafe.Pointer(pSel)).FpPrior
			}
		}
	} else {
		if (*TSelect)(unsafe.Pointer(pSubq)).FpWin != 0 && (*TWindow)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSubq)).FpWin)).FpPartition == uintptr(0) {
			return 0
		}
	}
	if (*TSelect)(unsafe.Pointer(pSubq)).FpLimit != uintptr(0) {
		return 0 /* restriction (3) */
	}
	for libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pWhere)).Fop) == int32(TK_AND) {
		nChng = nChng + _pushDownWhereTerms(tls, pParse, pSubq, (*TExpr)(unsafe.Pointer(pWhere)).FpRight, pSrcList, iSrc)
		pWhere = (*TExpr)(unsafe.Pointer(pWhere)).FpLeft
	}
	if _sqlite3ExprIsSingleTableConstraint(tls, pWhere, pSrcList, iSrc, int32(1)) != 0 {
		nChng = nChng + 1
		**(**Tu32)(__ccgo_up(pSubq + 4)) |= uint32(SF_PushDown)
		for pSubq != 0 {
			pNew = _sqlite3ExprDup(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pWhere, 0)
			_unsetJoinExpr(tls, pNew, -int32(1), int32(1))
			(**(**TSubstContext)(__ccgo_up(bp))).FpParse = pParse
			(**(**TSubstContext)(__ccgo_up(bp))).FiTable = (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor
			(**(**TSubstContext)(__ccgo_up(bp))).FiNewTable = (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor
			(**(**TSubstContext)(__ccgo_up(bp))).FisOuterJoin = 0
			(**(**TSubstContext)(__ccgo_up(bp))).FnSelDepth = 0
			(**(**TSubstContext)(__ccgo_up(bp))).FpEList = (*TSelect)(unsafe.Pointer(pSubq)).FpEList
			(**(**TSubstContext)(__ccgo_up(bp))).FpCList = _findLeftmostExprlist(tls, pSubq)
			pNew = _substExpr(tls, bp, pNew)
			if (*TParse)(unsafe.Pointer(pParse)).FnErr == 0 && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pNew)).Fop) == int32(TK_IN) && (*TExpr)(unsafe.Pointer(pNew)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
				**(**Tu32)(__ccgo_up(*(*uintptr)(unsafe.Pointer(pNew + 20)) + 4)) |= uint32(SF_ClonedRhsIn)
				**(**Tu32)(__ccgo_up(*(*uintptr)(unsafe.Pointer(pWhere + 20)) + 4)) |= uint32(SF_ClonedRhsIn)
			}
			if (*TSelect)(unsafe.Pointer(pSubq)).FpWin != 0 && 0 == _pushDownWindowCheck(tls, pParse, pSubq, pNew) {
				/* Restriction 6c has prevented push-down in this case */
				_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pNew)
				nChng = nChng - 1
				break
			}
			if (*TSelect)(unsafe.Pointer(pSubq)).FselFlags&uint32(SF_Aggregate) != 0 {
				(*TSelect)(unsafe.Pointer(pSubq)).FpHaving = _sqlite3ExprAnd(tls, pParse, (*TSelect)(unsafe.Pointer(pSubq)).FpHaving, pNew)
			} else {
				(*TSelect)(unsafe.Pointer(pSubq)).FpWhere = _sqlite3ExprAnd(tls, pParse, (*TSelect)(unsafe.Pointer(pSubq)).FpWhere, pNew)
			}
			pSubq = (*TSelect)(unsafe.Pointer(pSubq)).FpPrior
		}
	}
	return nChng
}

// C documentation
//
//	/*
//	** Generate code that will push the record in registers regData
//	** through regData+nData-1 onto the sorter.
//	*/
func _pushOntoSorter(tls *libc.TLS, pParse uintptr, pSort uintptr, pSelect uintptr, regData int32, regOrigData int32, nData int32, nPrefixReg int32) {
	var addrFirst, addrJmp, bSeq, iCsr, iLimit, iSkip, nBase, nExpr, nKey, nOBSat, op, regBase, regPrevKey, regRecord, v1 int32
	var pKI, pOp, v, v4 uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addrFirst, addrJmp, bSeq, iCsr, iLimit, iSkip, nBase, nExpr, nKey, nOBSat, op, pKI, pOp, regBase, regPrevKey, regRecord, v, v1, v4
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe /* Stmt under construction */
	bSeq = libc.BoolInt32(libc.Int32FromUint8((*TSortCtx)(unsafe.Pointer(pSort)).FsortFlags)&int32(SORTFLAG_UseSorter) == 0)
	nExpr = (*TExprList)(unsafe.Pointer((*TSortCtx)(unsafe.Pointer(pSort)).FpOrderBy)).FnExpr /* No. of ORDER BY terms */
	nBase = nExpr + bSeq + nData                                                              /* Regs for sorter record */
	regRecord = 0                                                                             /* Assembled sorter record */
	nOBSat = (*TSortCtx)(unsafe.Pointer(pSort)).FnOBSat                                       /* LIMIT counter */
	iSkip = 0                                                                                 /* End of the sorter insert loop */
	/* Three cases:
	 **   (1) The data to be sorted has already been packed into a Record
	 **       by a prior OP_MakeRecord.  In this case nData==1 and regData
	 **       will be completely unrelated to regOrigData.
	 **   (2) All output columns are included in the sort record.  In that
	 **       case regData==regOrigData.
	 **   (3) Some output columns are omitted from the sort record due to
	 **       the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
	 **       SQLITE_ECEL_OMITREF optimization, or due to the
	 **       SortCtx.pDeferredRowLoad optimization.  In any of these cases
	 **       regOrigData is 0 to prevent this routine from trying to copy
	 **       values that might not yet exist.
	 */
	if nPrefixReg != 0 {
		regBase = regData - nPrefixReg
	} else {
		regBase = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += nBase
	}
	if (*TSelect)(unsafe.Pointer(pSelect)).FiOffset != 0 {
		v1 = (*TSelect)(unsafe.Pointer(pSelect)).FiOffset + int32(1)
	} else {
		v1 = (*TSelect)(unsafe.Pointer(pSelect)).FiLimit
	}
	iLimit = v1
	(*TSortCtx)(unsafe.Pointer(pSort)).FlabelDone = _sqlite3VdbeMakeLabel(tls, pParse)
	if regOrigData != 0 {
		v1 = int32(SQLITE_ECEL_REF)
	} else {
		v1 = 0
	}
	_sqlite3ExprCodeExprList(tls, pParse, (*TSortCtx)(unsafe.Pointer(pSort)).FpOrderBy, regBase, regOrigData, libc.Uint8FromInt32(int32(SQLITE_ECEL_DUP)|v1))
	if bSeq != 0 {
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Sequence), (*TSortCtx)(unsafe.Pointer(pSort)).FiECursor, regBase+nExpr)
	}
	if nPrefixReg == 0 && nData > 0 {
		_sqlite3ExprCodeMove(tls, pParse, regData, regBase+nExpr+bSeq, nData)
	}
	if nOBSat > 0 { /* Original KeyInfo on the sorter table */
		regRecord = _makeSorterRecord(tls, pParse, pSort, pSelect, regBase, nBase)
		regPrevKey = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += (*TSortCtx)(unsafe.Pointer(pSort)).FnOBSat
		nKey = nExpr - (*TSortCtx)(unsafe.Pointer(pSort)).FnOBSat + bSeq
		if bSeq != 0 {
			addrFirst = _sqlite3VdbeAddOp1(tls, v, int32(OP_IfNot), regBase+nExpr)
		} else {
			addrFirst = _sqlite3VdbeAddOp1(tls, v, int32(OP_SequenceTest), (*TSortCtx)(unsafe.Pointer(pSort)).FiECursor)
		}
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Compare), regPrevKey, regBase, (*TSortCtx)(unsafe.Pointer(pSort)).FnOBSat)
		pOp = _sqlite3VdbeGetOp(tls, v, (*TSortCtx)(unsafe.Pointer(pSort)).FaddrSortIndex)
		if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
			return
		}
		(*TVdbeOp)(unsafe.Pointer(pOp)).Fp2 = nKey + nData
		pKI = *(*uintptr)(unsafe.Pointer(pOp + 16))
		libc.Xmemset(tls, (*TKeyInfo)(unsafe.Pointer(pKI)).FaSortFlags, 0, uint32((*TKeyInfo)(unsafe.Pointer(pKI)).FnKeyField)) /* Makes OP_Jump testable */
		_sqlite3VdbeChangeP4(tls, v, -int32(1), pKI, -int32(9))
		*(*uintptr)(unsafe.Pointer(pOp + 16)) = _sqlite3KeyInfoFromExprList(tls, pParse, (*TSortCtx)(unsafe.Pointer(pSort)).FpOrderBy, nOBSat, libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer(pKI)).FnAllField)-libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer(pKI)).FnKeyField)-int32(1))
		pOp = uintptr(0) /* Ensure pOp not used after sqlite3VdbeAddOp3() */
		addrJmp = _sqlite3VdbeCurrentAddr(tls, v)
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Jump), addrJmp+int32(1), 0, addrJmp+int32(1))
		(*TSortCtx)(unsafe.Pointer(pSort)).FlabelBkOut = _sqlite3VdbeMakeLabel(tls, pParse)
		v4 = pParse + 48
		*(*int32)(unsafe.Pointer(v4)) = *(*int32)(unsafe.Pointer(v4)) + 1
		v1 = *(*int32)(unsafe.Pointer(v4))
		(*TSortCtx)(unsafe.Pointer(pSort)).FregReturn = v1
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Gosub), (*TSortCtx)(unsafe.Pointer(pSort)).FregReturn, (*TSortCtx)(unsafe.Pointer(pSort)).FlabelBkOut)
		_sqlite3VdbeAddOp1(tls, v, int32(OP_ResetSorter), (*TSortCtx)(unsafe.Pointer(pSort)).FiECursor)
		if iLimit != 0 {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_IfNot), iLimit, (*TSortCtx)(unsafe.Pointer(pSort)).FlabelDone)
		}
		_sqlite3VdbeJumpHere(tls, v, addrFirst)
		_sqlite3ExprCodeMove(tls, pParse, regBase, regPrevKey, (*TSortCtx)(unsafe.Pointer(pSort)).FnOBSat)
		_sqlite3VdbeJumpHere(tls, v, addrJmp)
	}
	if iLimit != 0 {
		/* At this point the values for the new sorter entry are stored
		 ** in an array of registers. They need to be composed into a record
		 ** and inserted into the sorter if either (a) there are currently
		 ** less than LIMIT+OFFSET items or (b) the new record is smaller than
		 ** the largest record currently in the sorter. If (b) is true and there
		 ** are already LIMIT+OFFSET items in the sorter, delete the largest
		 ** entry before inserting the new one. This way there are never more
		 ** than LIMIT+OFFSET items in the sorter.
		 **
		 ** If the new record does not need to be inserted into the sorter,
		 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
		 ** value is not zero, then it is a label of where to jump.  Otherwise,
		 ** just bypass the row insert logic.  See the header comment on the
		 ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
		 */
		iCsr = (*TSortCtx)(unsafe.Pointer(pSort)).FiECursor
		_sqlite3VdbeAddOp2(tls, v, int32(OP_IfNotZero), iLimit, _sqlite3VdbeCurrentAddr(tls, v)+int32(4))
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Last), iCsr, 0)
		iSkip = _sqlite3VdbeAddOp4Int(tls, v, int32(OP_IdxLE), iCsr, 0, regBase+nOBSat, nExpr-nOBSat)
		_sqlite3VdbeAddOp1(tls, v, int32(OP_Delete), iCsr)
	}
	if regRecord == 0 {
		regRecord = _makeSorterRecord(tls, pParse, pSort, pSelect, regBase, nBase)
	}
	if libc.Int32FromUint8((*TSortCtx)(unsafe.Pointer(pSort)).FsortFlags)&int32(SORTFLAG_UseSorter) != 0 {
		op = int32(OP_SorterInsert)
	} else {
		op = int32(OP_IdxInsert)
	}
	_sqlite3VdbeAddOp4Int(tls, v, op, (*TSortCtx)(unsafe.Pointer(pSort)).FiECursor, regRecord, regBase+nOBSat, nBase-nOBSat)
	if iSkip != 0 {
		if (*TSortCtx)(unsafe.Pointer(pSort)).FlabelOBLopt != 0 {
			v1 = (*TSortCtx)(unsafe.Pointer(pSort)).FlabelOBLopt
		} else {
			v1 = _sqlite3VdbeCurrentAddr(tls, v)
		}
		_sqlite3VdbeChangeP2(tls, v, iSkip, v1)
	}
}

// C documentation
//
//	/*
//	** Query to see if Btree handle p may obtain a lock of type eLock
//	** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
//	** SQLITE_OK if the lock may be obtained (by calling
//	** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
//	*/
func _querySharedCacheTableLock(tls *libc.TLS, p uintptr, iTab TPgno, eLock Tu8) (r int32) {
	var pBt, pIter, v2 uintptr
	_, _, _ = pBt, pIter, v2
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	/* If requesting a write-lock, then the Btree must have an open write
	 ** transaction on this file. And, obviously, for this to be so there
	 ** must be an open write transaction on the file itself.
	 */
	/* This routine is a no-op if the shared-cache is not enabled */
	if !((*TBtree)(unsafe.Pointer(p)).Fsharable != 0) {
		return SQLITE_OK
	}
	/* If some other connection is holding an exclusive lock, the
	 ** requested lock may not be obtained.
	 */
	if (*TBtShared)(unsafe.Pointer(pBt)).FpWriter != p && libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_EXCLUSIVE) != 0 {
		_sqlite3ConnectionBlocked(tls, (*TBtree)(unsafe.Pointer(p)).Fdb, (*TBtree)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpWriter)).Fdb)
		return libc.Int32FromInt32(SQLITE_LOCKED) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
	}
	pIter = (*TBtShared)(unsafe.Pointer(pBt)).FpLock
	for {
		if !(pIter != 0) {
			break
		}
		/* The condition (pIter->eLock!=eLock) in the following if(...)
		 ** statement is a simplification of:
		 **
		 **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
		 **
		 ** since we know that if eLock==WRITE_LOCK, then no other connection
		 ** may hold a WRITE_LOCK on any table in this file (since there can
		 ** only be a single writer).
		 */
		if (*TBtLock)(unsafe.Pointer(pIter)).FpBtree != p && (*TBtLock)(unsafe.Pointer(pIter)).FiTable == iTab && libc.Int32FromUint8((*TBtLock)(unsafe.Pointer(pIter)).FeLock) != libc.Int32FromUint8(eLock) {
			_sqlite3ConnectionBlocked(tls, (*TBtree)(unsafe.Pointer(p)).Fdb, (*TBtree)(unsafe.Pointer((*TBtLock)(unsafe.Pointer(pIter)).FpBtree)).Fdb)
			if libc.Int32FromUint8(eLock) == int32(WRITE_LOCK) {
				v2 = pBt + 24
				*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(BTS_PENDING))
			}
			return libc.Int32FromInt32(SQLITE_LOCKED) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
		}
		goto _1
	_1:
		;
		pIter = (*TBtLock)(unsafe.Pointer(pIter)).FpNext
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Compare two constraint names.
//	**
//	** Summary:   *pRes := zQuote != zCmp
//	**
//	** Details:
//	** Compare the (possibly quoted) constraint name zQuote[0..nQuote-1]
//	** against zCmp[].  Write zero into *pRes if they are the same and
//	** non-zero if they differ.  Normally return SQLITE_OK, except if there
//	** is an OOM, set the OOM error condition on ctx and return SQLITE_NOMEM.
//	*/
func _quotedCompare(tls *libc.TLS, ctx uintptr, t int32, zQuote uintptr, nQuote int32, zCmp uintptr, pRes uintptr) (r int32) {
	var zCopy uintptr
	_ = zCopy
	zCopy = uintptr(0) /* De-quoted, zero-terminated copy of zQuote[] */
	if t == int32(TK_ILLEGAL) {
		**(**int32)(__ccgo_up(pRes)) = int32(1)
		return SQLITE_OK
	}
	zCopy = _sqlite3MallocZero(tls, libc.Uint64FromInt32(nQuote+int32(1)))
	if zCopy == uintptr(0) {
		Xsqlite3_result_error_nomem(tls, ctx)
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemcpy(tls, zCopy, zQuote, libc.Uint32FromInt32(nQuote))
	_sqlite3Dequote(tls, zCopy)
	**(**int32)(__ccgo_up(pRes)) = Xsqlite3_stricmp(tls, zCopy, zCmp)
	Xsqlite3_free(tls, zCopy)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
//	** there is room for at least nCol elements. If an OOM occurs, store an
//	** error code in the RBU handle passed as the first argument.
//	*/
func _rbuAllocateIterArrays(tls *libc.TLS, p uintptr, pIter uintptr, nCol int32) {
	var azNew uintptr
	var nByte Tsqlite3_int64
	_, _ = azNew, nByte
	nByte = libc.Int64FromUint32((libc.Uint32FromInt32(2)*libc.Uint32FromInt64(4) + libc.Uint32FromInt64(4) + libc.Uint32FromInt32(3)*libc.Uint32FromInt64(1)) * libc.Uint32FromInt32(nCol))
	azNew = _rbuMalloc(tls, p, nByte)
	if azNew != 0 {
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FazTblCol = azNew
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FazTblType = azNew + uintptr(nCol)*4
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FaiSrcOrder = (*TRbuObjIter)(unsafe.Pointer(pIter)).FazTblType + uintptr(nCol)*4
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FabTblPk = (*TRbuObjIter)(unsafe.Pointer(pIter)).FaiSrcOrder + uintptr(nCol)*4
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FabNotNull = (*TRbuObjIter)(unsafe.Pointer(pIter)).FabTblPk + uintptr(nCol)
		(*TRbuObjIter)(unsafe.Pointer(pIter)).FabIndexed = (*TRbuObjIter)(unsafe.Pointer(pIter)).FabNotNull + uintptr(nCol)
	}
}

// C documentation
//
//	/*
//	** Called when iAmt bytes are read from offset iOff of the wal file while
//	** the rbu object is in capture mode. Record the frame number of the frame
//	** being read in the aFrame[] array.
//	*/
func _rbuCaptureWalRead(tls *libc.TLS, pRbu uintptr, iOff Ti64, iAmt int32) (r int32) {
	var aNew uintptr
	var iFrame, mReq Tu32
	var nNew, v1 int32
	_, _, _, _, _ = aNew, iFrame, mReq, nNew, v1
	mReq = libc.Uint32FromInt32(libc.Int32FromInt32(1)<<libc.Int32FromInt32(WAL_LOCK_WRITE) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(WAL_LOCK_CKPT) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(WAL_LOCK_READ0))
	if (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FmLock != mReq {
		(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).Frc = int32(SQLITE_BUSY)
		return libc.Int32FromInt32(SQLITE_NOTICE) | libc.Int32FromInt32(3)<<libc.Int32FromInt32(8)
	}
	(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).Fpgsz = iAmt
	if (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrame == (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrameAlloc {
		if (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrameAlloc != 0 {
			v1 = (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrameAlloc
		} else {
			v1 = int32(64)
		}
		nNew = v1 * int32(2)
		aNew = Xsqlite3_realloc64(tls, (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FaFrame, uint64(libc.Uint32FromInt32(nNew)*uint32(8)))
		if aNew == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FaFrame = aNew
		(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrameAlloc = nNew
	}
	iFrame = libc.Uint32FromInt64((iOff-libc.Int64FromInt32(32))/int64(iAmt+libc.Int32FromInt32(24))) + uint32(1)
	if (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FiMaxFrame < iFrame {
		(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FiMaxFrame = iFrame
	}
	(**(**TRbuFrame)(__ccgo_up((*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FaFrame + uintptr((*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrame)*8))).FiWalFrame = iFrame
	(**(**TRbuFrame)(__ccgo_up((*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FaFrame + uintptr((*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrame)*8))).FiDbPage = uint32(0)
	(*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrame = (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FnFrame + 1
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Read bytes from *pz and convert them into a positive integer.  When
//	** finished, leave *pz pointing to the first character past the end of
//	** the integer.  The *pLen parameter holds the length of the string
//	** in *pz and is decremented once for each character in the integer.
//	*/
func _rbuDeltaGetInt(tls *libc.TLS, pz uintptr, pLen uintptr) (r uint32) {
	var c, v1 int32
	var v uint32
	var z, zEnd uintptr
	var v2 bool
	_, _, _, _, _, _ = c, v, z, zEnd, v1, v2
	v = uint32(0)
	z = **(**uintptr)(__ccgo_up(pz))
	zEnd = z + uintptr(**(**int32)(__ccgo_up(pLen)))
	for {
		if v2 = z < zEnd; v2 {
			v1 = int32(_zValue[**(**uint8)(__ccgo_up(z))])
			c = v1
		}
		if !(v2 && v1 >= 0) {
			break
		}
		v = v<<int32(6) + libc.Uint32FromInt32(c)
		z = z + 1
	}
	**(**int32)(__ccgo_up(pLen)) -= int32(z) - int32(**(**uintptr)(__ccgo_up(pz)))
	**(**uintptr)(__ccgo_up(pz)) = z
	return v
}

// C documentation
//
//	/*
//	** Attempt to allocate and return a pointer to a zeroed block of nByte
//	** bytes.
//	**
//	** If an error (i.e. an OOM condition) occurs, return NULL and leave an
//	** error code in the rbu handle passed as the first argument. Or, if an
//	** error has already occurred when this function is called, return NULL
//	** immediately without attempting the allocation or modifying the stored
//	** error code.
//	*/
func _rbuMalloc(tls *libc.TLS, p uintptr, nByte Tsqlite3_int64) (r uintptr) {
	var pRet uintptr
	_ = pRet
	pRet = uintptr(0)
	if (*Tsqlite3rbu)(unsafe.Pointer(p)).Frc == SQLITE_OK {
		pRet = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if pRet == uintptr(0) {
			(*Tsqlite3rbu)(unsafe.Pointer(p)).Frc = int32(SQLITE_NOMEM)
		} else {
			libc.Xmemset(tls, pRet, 0, libc.Uint32FromInt64(nByte))
		}
	}
	return pRet
}

// C documentation
//
//	/*
//	** Read data from an rbuVfs-file.
//	*/
func _rbuVfsRead(tls *libc.TLS, pFile uintptr, zBuf uintptr, iAmt int32, iOfst Tsqlite_int64) (r int32) {
	var aBuf, p, pBuf, pFd, pRbu uintptr
	var iRoot Tu32
	var rc, v1 int32
	_, _, _, _, _, _, _, _ = aBuf, iRoot, p, pBuf, pFd, pRbu, rc, v1
	p = pFile
	pRbu = (*Trbu_file)(unsafe.Pointer(p)).FpRbu
	if pRbu != 0 && (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FeStage == int32(RBU_STAGE_CAPTURE) {
		rc = _rbuCaptureWalRead(tls, (*Trbu_file)(unsafe.Pointer(p)).FpRbu, iOfst, iAmt)
	} else {
		if pRbu != 0 && (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FeStage == int32(RBU_STAGE_OAL) && (*Trbu_file)(unsafe.Pointer(p)).FopenFlags&int32(SQLITE_OPEN_WAL) != 0 && iOfst >= (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FiOalSz {
			rc = SQLITE_OK
			libc.Xmemset(tls, zBuf, 0, libc.Uint32FromInt32(iAmt))
		} else {
			rc = (*(*func(*libc.TLS, uintptr, uintptr, int32, Tsqlite3_int64) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_io_methods)(unsafe.Pointer((*Tsqlite3_file)(unsafe.Pointer((*Trbu_file)(unsafe.Pointer(p)).FpReal)).FpMethods)).FxRead})))(tls, (*Trbu_file)(unsafe.Pointer(p)).FpReal, zBuf, iAmt, iOfst)
			/* If this is being called to read the first page of the target
			 ** database as part of an rbu vacuum operation, synthesize the
			 ** contents of the first page if it does not yet exist. Otherwise,
			 ** SQLite will not check for a *-wal file.  */
			if pRbu != 0 && (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FzTarget == uintptr(0) && rc == libc.Int32FromInt32(SQLITE_IOERR)|libc.Int32FromInt32(2)<<libc.Int32FromInt32(8) && iOfst == 0 && (*Trbu_file)(unsafe.Pointer(p)).FopenFlags&int32(SQLITE_OPEN_MAIN_DB) != 0 && (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).Frc == SQLITE_OK {
				pFd = (*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FpRbuFd
				rc = (*(*func(*libc.TLS, uintptr, uintptr, int32, Tsqlite3_int64) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_io_methods)(unsafe.Pointer((*Tsqlite3_file)(unsafe.Pointer(pFd)).FpMethods)).FxRead})))(tls, pFd, zBuf, iAmt, iOfst)
				if rc == SQLITE_OK {
					aBuf = zBuf
					if _rbuGetU32(tls, aBuf+52) != 0 {
						v1 = int32(1)
					} else {
						v1 = 0
					}
					iRoot = libc.Uint32FromInt32(v1)
					_rbuPutU32(tls, aBuf+52, iRoot)                                                                                         /* largest root page number */
					_rbuPutU32(tls, aBuf+36, uint32(0))                                                                                     /* number of free pages */
					_rbuPutU32(tls, aBuf+32, uint32(0))                                                                                     /* first page on free list trunk */
					_rbuPutU32(tls, aBuf+28, uint32(1))                                                                                     /* size of db file in pages */
					_rbuPutU32(tls, aBuf+24, (*Trbu_file)(unsafe.Pointer((*Tsqlite3rbu)(unsafe.Pointer(pRbu)).FpRbuFd)).FiCookie+uint32(1)) /* Change counter */
					if iAmt > int32(100) {
						libc.Xmemset(tls, aBuf+100, 0, libc.Uint32FromInt32(iAmt-int32(100)))
						_rbuPutU16(tls, aBuf+105, libc.Uint16FromInt32(iAmt&int32(0xFFFF)))
						**(**Tu8)(__ccgo_up(aBuf + 100)) = uint8(0x0D)
					}
				}
			}
		}
		if rc == SQLITE_OK && iOfst == 0 && (*Trbu_file)(unsafe.Pointer(p)).FopenFlags&int32(SQLITE_OPEN_MAIN_DB) != 0 {
			/* These look like magic numbers. But they are stable, as they are part
			 ** of the definition of the SQLite file format, which may not change. */
			pBuf = zBuf
			(*Trbu_file)(unsafe.Pointer(p)).FiCookie = _rbuGetU32(tls, pBuf+24)
			(*Trbu_file)(unsafe.Pointer(p)).FiWriteVer = **(**Tu8)(__ccgo_up(pBuf + 19))
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
//	*/
func _rbuVfsShmMap(tls *libc.TLS, pFile uintptr, iRegion int32, szRegion int32, isWrite int32, pp uintptr) (r int32) {
	var apNew, p, pNew uintptr
	var eStage, rc, v1 int32
	var nByte Tsqlite3_int64
	_, _, _, _, _, _, _ = apNew, eStage, nByte, p, pNew, rc, v1
	p = pFile
	rc = SQLITE_OK
	if (*Trbu_file)(unsafe.Pointer(p)).FpRbu != 0 {
		v1 = (*Tsqlite3rbu)(unsafe.Pointer((*Trbu_file)(unsafe.Pointer(p)).FpRbu)).FeStage
	} else {
		v1 = 0
	}
	eStage = v1
	/* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
	 ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
	 ** instead of a file on disk.  */
	if eStage == int32(RBU_STAGE_OAL) {
		nByte = libc.Int64FromUint32(libc.Uint32FromInt32(iRegion+libc.Int32FromInt32(1)) * uint32(4))
		apNew = Xsqlite3_realloc64(tls, (*Trbu_file)(unsafe.Pointer(p)).FapShm, libc.Uint64FromInt64(nByte))
		/* This is an RBU connection that uses its own heap memory for the
		 ** pages of the *-shm file. Since no other process can have run
		 ** recovery, the connection must request *-shm pages in order
		 ** from start to finish.  */
		if apNew == uintptr(0) {
			rc = int32(SQLITE_NOMEM)
		} else {
			libc.Xmemset(tls, apNew+uintptr((*Trbu_file)(unsafe.Pointer(p)).FnShm)*4, 0, uint32(4)*libc.Uint32FromInt32(libc.Int32FromInt32(1)+iRegion-(*Trbu_file)(unsafe.Pointer(p)).FnShm))
			(*Trbu_file)(unsafe.Pointer(p)).FapShm = apNew
			(*Trbu_file)(unsafe.Pointer(p)).FnShm = iRegion + int32(1)
		}
		if rc == SQLITE_OK {
			pNew = Xsqlite3_malloc64(tls, libc.Uint64FromInt32(szRegion))
			if pNew == uintptr(0) {
				rc = int32(SQLITE_NOMEM)
			} else {
				libc.Xmemset(tls, pNew, 0, libc.Uint32FromInt32(szRegion))
				**(**uintptr)(__ccgo_up((*Trbu_file)(unsafe.Pointer(p)).FapShm + uintptr(iRegion)*4)) = pNew
			}
		}
		if rc == SQLITE_OK {
			**(**uintptr)(__ccgo_up(pp)) = **(**uintptr)(__ccgo_up((*Trbu_file)(unsafe.Pointer(p)).FapShm + uintptr(iRegion)*4))
		} else {
			**(**uintptr)(__ccgo_up(pp)) = uintptr(0)
		}
	} else {
		rc = (*(*func(*libc.TLS, uintptr, int32, int32, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_io_methods)(unsafe.Pointer((*Tsqlite3_file)(unsafe.Pointer((*Trbu_file)(unsafe.Pointer(p)).FpReal)).FpMethods)).FxShmMap})))(tls, (*Trbu_file)(unsafe.Pointer(p)).FpReal, iRegion, szRegion, isWrite, pp)
	}
	return rc
}

// C documentation
//
//	/*
//	** Array apCell[] contains pointers to nCell b-tree page cells. The
//	** szCell[] array contains the size in bytes of each cell. This function
//	** replaces the current contents of page pPg with the contents of the cell
//	** array.
//	**
//	** Some of the cells in apCell[] may currently be stored in pPg. This
//	** function works around problems caused by this by making a copy of any
//	** such cells before overwriting the page data.
//	**
//	** The MemPage.nFree field is invalidated by this function. It is the
//	** responsibility of the caller to set it correctly.
//	*/
func _rebuildPage(tls *libc.TLS, pCArray uintptr, iFirst int32, nCell int32, pPg uintptr) (r int32) {
	var aData, pCell, pCellptr, pData, pEnd, pSrcEnd, pTmp uintptr
	var hdr, i, iEnd, k, usableSize int32
	var j Tu32
	var sz Tu16
	_, _, _, _, _, _, _, _, _, _, _, _, _, _ = aData, hdr, i, iEnd, j, k, pCell, pCellptr, pData, pEnd, pSrcEnd, pTmp, sz, usableSize
	hdr = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPg)).FhdrOffset) /* Offset of header on pPg */
	aData = (*TMemPage)(unsafe.Pointer(pPg)).FaData                        /* Pointer to data for pPg */
	usableSize = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPg)).FpBt)).FusableSize)
	pEnd = aData + uintptr(usableSize)
	i = iFirst       /* Start of cell content area */
	iEnd = i + nCell /* Loop terminator */
	pCellptr = (*TMemPage)(unsafe.Pointer(pPg)).FaCellIdx
	pTmp = _sqlite3PagerTempSpace(tls, (*TBtShared)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(pPg)).FpBt)).FpPager) /* Current pCArray->apEnd[k] value */
	j = libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)))))<<libc.Int32FromInt32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)) + 1))))
	if j > libc.Uint32FromInt32(usableSize) {
		j = uint32(0)
	}
	libc.Xmemcpy(tls, pTmp+uintptr(j), aData+uintptr(j), libc.Uint32FromInt32(usableSize)-j)
	k = 0
	for {
		if !(**(**int32)(__ccgo_up(pCArray + 40 + uintptr(k)*4)) <= i) {
			break
		}
		goto _1
	_1:
		;
		k = k + 1
	}
	pSrcEnd = **(**uintptr)(__ccgo_up(pCArray + 16 + uintptr(k)*4))
	pData = pEnd
	for int32(1) != 0 {
		pCell = **(**uintptr)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FapCell + uintptr(i)*4))
		sz = **(**Tu16)(__ccgo_up((*TCellArray)(unsafe.Pointer(pCArray)).FszCell + uintptr(i)*2))
		if uint32(pCell) >= uint32(aData+uintptr(j)) && uint32(pCell) < uint32(pEnd) {
			if uint32(pCell+uintptr(sz)) > uint32(pEnd) {
				return _sqlite3CorruptError(tls, int32(80905))
			}
			pCell = pTmp + uintptr(int32(pCell)-int32(aData))
		} else {
			if uint32(pCell+uintptr(sz)) > uint32(pSrcEnd) && uint32(pCell) < uint32(pSrcEnd) {
				return _sqlite3CorruptError(tls, int32(80910))
			}
		}
		pData = pData - uintptr(sz)
		**(**Tu8)(__ccgo_up(pCellptr)) = libc.Uint8FromInt32((int32(pData) - int32(aData)) >> libc.Int32FromInt32(8))
		**(**Tu8)(__ccgo_up(pCellptr + 1)) = libc.Uint8FromInt32(int32(pData) - int32(aData))
		pCellptr = pCellptr + uintptr(2)
		if pData < pCellptr {
			return _sqlite3CorruptError(tls, int32(80916))
		}
		libc.Xmemmove(tls, pData, pCell, uint32(sz))
		i = i + 1
		if i >= iEnd {
			break
		}
		if **(**int32)(__ccgo_up(pCArray + 40 + uintptr(k)*4)) <= i {
			k = k + 1
			pSrcEnd = **(**uintptr)(__ccgo_up(pCArray + 16 + uintptr(k)*4))
		}
	}
	/* The pPg->nFree field is now set incorrectly. The caller will fix it. */
	(*TMemPage)(unsafe.Pointer(pPg)).FnCell = libc.Uint16FromInt32(nCell)
	(*TMemPage)(unsafe.Pointer(pPg)).FnOverflow = uint8(0)
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(1)))) = libc.Uint8FromInt32(libc.Int32FromInt32(0) >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(1)) + 1)) = libc.Uint8FromInt32(libc.Int32FromInt32(0))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(3)))) = libc.Uint8FromInt32(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPg)).FnCell) >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(3)) + 1)) = uint8((*TMemPage)(unsafe.Pointer(pPg)).FnCell)
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)))) = libc.Uint8FromInt32((int32(pData) - int32(aData)) >> libc.Int32FromInt32(8))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(5)) + 1)) = libc.Uint8FromInt32(int32(pData) - int32(aData))
	**(**Tu8)(__ccgo_up(aData + uintptr(hdr+int32(7)))) = uint8(0x00)
	return SQLITE_OK
}

// C documentation
//
//	/* Recompute the colNotIdxed field of the Index.
//	**
//	** colNotIdxed is a bitmask that has a 0 bit representing each indexed
//	** columns that are within the first 63 columns of the table and a 1 for
//	** all other bits (all columns that are not in the index).  The
//	** high-order bit of colNotIdxed is always 1.  All unindexed columns
//	** of the table have a 1.
//	**
//	** 2019-10-24:  For the purpose of this computation, virtual columns are
//	** not considered to be covered by the index, even if they are in the
//	** index, because we do not trust the logic in whereIndexExprTrans() to be
//	** able to find all instances of a reference to the indexed table column
//	** and convert them into references to the index.  Hence we always want
//	** the actual table at hand in order to recompute the virtual column, if
//	** necessary.
//	**
//	** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
//	** to determine if the index is covering index.
//	*/
func _recomputeColumnsNotIndexed(tls *libc.TLS, pIdx uintptr) {
	var j, x int32
	var m TBitmask
	var pTab uintptr
	_, _, _, _ = j, m, pTab, x
	m = uint64(0)
	pTab = (*TIndex)(unsafe.Pointer(pIdx)).FpTable
	j = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn) - int32(1)
	for {
		if !(j >= 0) {
			break
		}
		x = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(j)*2)))
		if x >= 0 && libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(x)*12))).FcolFlags)&int32(COLFLAG_VIRTUAL) == 0 {
			if x < libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8))-libc.Int32FromInt32(1) {
				m = m | libc.Uint64FromInt32(1)<<x
			}
		}
		goto _1
	_1:
		;
		j = j - 1
	}
	(*TIndex)(unsafe.Pointer(pIdx)).FcolNotIdxed = ^m
	/* See note-20221022-a */
}

// C documentation
//
//	/*
//	** pSelect is a SELECT statement and pSrcItem is one item in the FROM
//	** clause of that SELECT.
//	**
//	** This routine scans the entire SELECT statement and recomputes the
//	** pSrcItem->colUsed mask.
//	*/
func _recomputeColumnsUsedExpr(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pItem uintptr
	_ = pItem
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_COLUMN) {
		return WRC_Continue
	}
	pItem = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	if (*TSrcItem)(unsafe.Pointer(pItem)).FiCursor != (*TExpr)(unsafe.Pointer(pExpr)).FiTable {
		return WRC_Continue
	}
	if int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) < 0 {
		return WRC_Continue
	}
	**(**TBitmask)(__ccgo_up(pItem + 24)) |= _sqlite3ExprColUsed(tls, pExpr)
	return WRC_Continue
}

// C documentation
//
//	/* Resize the hash table so that it contains "new_size" buckets.
//	**
//	** The hash table might fail to resize if sqlite3_malloc() fails or
//	** if the new size is the same as the prior size.
//	** Return TRUE if the resize occurs and false if not.
//	*/
func _rehash(tls *libc.TLS, pH uintptr, new_size uint32) (r int32) {
	var elem, new_ht, next_elem uintptr
	var v1 uint32
	_, _, _, _ = elem, new_ht, next_elem, v1 /* For looping over existing elements */
	if new_size*uint32(8) > uint32(SQLITE_MALLOC_SOFT_LIMIT) {
		new_size = libc.Uint32FromInt32(SQLITE_MALLOC_SOFT_LIMIT) / libc.Uint32FromInt64(8)
	}
	if new_size == (*THash)(unsafe.Pointer(pH)).Fhtsize {
		return 0
	}
	/* The inability to allocates space for a larger hash table is
	 ** a performance hit but it is not a fatal error.  So mark the
	 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
	 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
	 ** only zeroes the requested number of bytes whereas this module will
	 ** use the actual amount of space allocated for the hash table (which
	 ** may be larger than the requested amount).
	 */
	_sqlite3BeginBenignMalloc(tls)
	new_ht = _sqlite3Malloc(tls, uint64(new_size*uint32(8)))
	_sqlite3EndBenignMalloc(tls)
	if new_ht == uintptr(0) {
		return 0
	}
	Xsqlite3_free(tls, (*THash)(unsafe.Pointer(pH)).Fht)
	(*THash)(unsafe.Pointer(pH)).Fht = new_ht
	v1 = libc.Uint32FromInt32(_sqlite3MallocSize(tls, new_ht)) / libc.Uint32FromInt64(8)
	new_size = v1
	(*THash)(unsafe.Pointer(pH)).Fhtsize = v1
	libc.Xmemset(tls, new_ht, 0, new_size*uint32(8))
	elem = (*THash)(unsafe.Pointer(pH)).Ffirst
	(*THash)(unsafe.Pointer(pH)).Ffirst = libc.UintptrFromInt32(0)
	for {
		if !(elem != 0) {
			break
		}
		next_elem = (*THashElem)(unsafe.Pointer(elem)).Fnext
		_insertElement(tls, pH, new_ht+uintptr((*THashElem)(unsafe.Pointer(elem)).Fh%new_size)*8, elem)
		goto _2
	_2:
		;
		elem = next_elem
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** Release auxiliary memory held in an array of N Mem elements.
//	**
//	** After this routine returns, all Mem elements in the array will still
//	** be valid.  Those Mem elements that were not holding auxiliary resources
//	** will be unchanged.  Mem elements which had something freed will be
//	** set to MEM_Undefined.
//	*/
func _releaseMemArray(tls *libc.TLS, p uintptr, N int32) {
	var db, pEnd, v1 uintptr
	_, _, _ = db, pEnd, v1
	if p != 0 && N != 0 {
		pEnd = p + uintptr(N)*40
		db = (*TMem)(unsafe.Pointer(p)).Fdb
		if (*Tsqlite3)(unsafe.Pointer(db)).FpnBytesFreed != 0 {
			for {
				if (*TMem)(unsafe.Pointer(p)).FszMalloc != 0 {
					_sqlite3DbFree(tls, db, (*TMem)(unsafe.Pointer(p)).FzMalloc)
				}
				goto _2
			_2:
				;
				p += 40
				v1 = p
				if !(v1 < pEnd) {
					break
				}
			}
			return
		}
		for {
			/* This block is really an inlined version of sqlite3VdbeMemRelease()
			 ** that takes advantage of the fact that the memory cell value is
			 ** being set to NULL after releasing any dynamic resources.
			 **
			 ** The justification for duplicating code is that according to
			 ** callgrind, this causes a certain test case to hit the CPU 4.7
			 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
			 ** sqlite3MemRelease() were called from here. With -O2, this jumps
			 ** to 6.6 percent. The test case is inserting 1000 rows into a table
			 ** with no indexes using a single prepared INSERT statement, bind()
			 ** and reset(). Inserts are grouped into a transaction.
			 */
			if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(MEM_Agg)|libc.Int32FromInt32(MEM_Dyn)) != 0 {
				_sqlite3VdbeMemRelease(tls, p)
				(*TMem)(unsafe.Pointer(p)).Fflags = uint16(MEM_Undefined)
			} else {
				if (*TMem)(unsafe.Pointer(p)).FszMalloc != 0 {
					_sqlite3DbNNFreeNN(tls, db, (*TMem)(unsafe.Pointer(p)).FzMalloc)
					(*TMem)(unsafe.Pointer(p)).FszMalloc = 0
					(*TMem)(unsafe.Pointer(p)).Fflags = uint16(MEM_Undefined)
				}
			}
			goto _4
		_4:
			;
			p += 40
			v1 = p
			if !(v1 < pEnd) {
				break
			}
		}
	}
}

// C documentation
//
//	/*
//	** Move the open database page pDbPage to location iFreePage in the
//	** database. The pDbPage reference remains valid.
//	**
//	** The isCommit flag indicates that there is no need to remember that
//	** the journal needs to be sync()ed before database page pDbPage->pgno
//	** can be written to. The caller has already promised not to write to that
//	** page.
//	*/
func _relocatePage(tls *libc.TLS, pBt uintptr, pDbPage uintptr, eType Tu8, iPtrPage TPgno, iFreePage TPgno, isCommit int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iDbPage, nextOvfl TPgno
	var pPager uintptr
	var _ /* pPtrPage at bp+0 */ uintptr
	var _ /* rc at bp+4 */ int32
	_, _, _ = iDbPage, nextOvfl, pPager /* The page that contains a pointer to pDbPage */
	iDbPage = (*TMemPage)(unsafe.Pointer(pDbPage)).Fpgno
	pPager = (*TBtShared)(unsafe.Pointer(pBt)).FpPager
	if iDbPage < uint32(3) {
		return _sqlite3CorruptError(tls, int32(77187))
	}
	/* Move page iDbPage from its current location to page number iFreePage */
	**(**int32)(__ccgo_up(bp + 4)) = _sqlite3PagerMovepage(tls, pPager, (*TMemPage)(unsafe.Pointer(pDbPage)).FpDbPage, iFreePage, isCommit)
	if **(**int32)(__ccgo_up(bp + 4)) != SQLITE_OK {
		return **(**int32)(__ccgo_up(bp + 4))
	}
	(*TMemPage)(unsafe.Pointer(pDbPage)).Fpgno = iFreePage
	/* If pDbPage was a btree-page, then it may have child pages and/or cells
	 ** that point to overflow pages. The pointer map entries for all these
	 ** pages need to be changed.
	 **
	 ** If pDbPage is an overflow page, then the first 4 bytes may store a
	 ** pointer to a subsequent overflow page. If this is the case, then
	 ** the pointer map needs to be updated for the subsequent overflow page.
	 */
	if libc.Int32FromUint8(eType) == int32(PTRMAP_BTREE) || libc.Int32FromUint8(eType) == int32(PTRMAP_ROOTPAGE) {
		**(**int32)(__ccgo_up(bp + 4)) = _setChildPtrmaps(tls, pDbPage)
		if **(**int32)(__ccgo_up(bp + 4)) != SQLITE_OK {
			return **(**int32)(__ccgo_up(bp + 4))
		}
	} else {
		nextOvfl = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pDbPage)).FaData)
		if nextOvfl != uint32(0) {
			_ptrmapPut(tls, pBt, nextOvfl, uint8(PTRMAP_OVERFLOW2), iFreePage, bp+4)
			if **(**int32)(__ccgo_up(bp + 4)) != SQLITE_OK {
				return **(**int32)(__ccgo_up(bp + 4))
			}
		}
	}
	/* Fix the database pointer on page iPtrPage that pointed at iDbPage so
	 ** that it points at iFreePage. Also fix the pointer map entry for
	 ** iPtrPage.
	 */
	if libc.Int32FromUint8(eType) != int32(PTRMAP_ROOTPAGE) {
		**(**int32)(__ccgo_up(bp + 4)) = _btreeGetPage(tls, pBt, iPtrPage, bp, 0)
		if **(**int32)(__ccgo_up(bp + 4)) != SQLITE_OK {
			return **(**int32)(__ccgo_up(bp + 4))
		}
		**(**int32)(__ccgo_up(bp + 4)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpDbPage)
		if **(**int32)(__ccgo_up(bp + 4)) != SQLITE_OK {
			_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
			return **(**int32)(__ccgo_up(bp + 4))
		}
		**(**int32)(__ccgo_up(bp + 4)) = _modifyPagePointer(tls, **(**uintptr)(__ccgo_up(bp)), iDbPage, iFreePage, eType)
		_releasePage(tls, **(**uintptr)(__ccgo_up(bp)))
		if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK {
			_ptrmapPut(tls, pBt, iFreePage, eType, iPtrPage, bp+4)
		}
	}
	return **(**int32)(__ccgo_up(bp + 4))
}

// C documentation
//
//	/*
//	** pX is an expression of the form:  (vector) IN (SELECT ...)
//	** In other words, it is a vector IN operator with a SELECT clause on the
//	** RHS.  But not all terms in the vector are indexable and the terms might
//	** not be in the correct order for indexing.
//	**
//	** This routine makes a copy of the input pX expression and then adjusts
//	** the vector on the LHS with corresponding changes to the SELECT so that
//	** the vector contains only index terms and those terms are in the correct
//	** order.  The modified IN expression is returned.  The caller is responsible
//	** for deleting the returned expression.
//	**
//	** Example:
//	**
//	**    CREATE TABLE t1(a,b,c,d,e,f);
//	**    CREATE INDEX t1x1 ON t1(e,c);
//	**    SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
//	**                           \_______________________________________/
//	**                                     The pX expression
//	**
//	** Since only columns e and c can be used with the index, in that order,
//	** the modified IN expression that is returned will be:
//	**
//	**        (e,c) IN (SELECT z,x FROM t2)
//	**
//	** The reduced pX is different from the original (obviously) and thus is
//	** only used for indexing, to improve performance.  The original unaltered
//	** IN expression must also be run on each output row for correctness.
//	*/
func _removeUnindexableInClauseTerms(tls *libc.TLS, pParse uintptr, iEq int32, pLoop uintptr, pX uintptr) (r uintptr) {
	var db, p, pLhs, pNew, pOrigLhs, pOrigRhs, pRhs, pSelect, v4 uintptr
	var i, iField, v3 int32
	_, _, _, _, _, _, _, _, _, _, _, _ = db, i, iField, p, pLhs, pNew, pOrigLhs, pOrigRhs, pRhs, pSelect, v3, v4
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	pNew = _sqlite3ExprDup(tls, db, pX, 0)
	if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
		pSelect = *(*uintptr)(unsafe.Pointer(pNew + 20))
		for {
			if !(pSelect != 0) {
				break
			} /* Original unmodified RHS */
			pOrigLhs = uintptr(0) /* Original unmodified LHS */
			pRhs = uintptr(0)     /* New RHS after modifications */
			pLhs = uintptr(0)     /* Loop counter */
			pOrigRhs = (*TSelect)(unsafe.Pointer(pSelect)).FpEList
			if pSelect == *(*uintptr)(unsafe.Pointer(pNew + 20)) {
				pOrigLhs = *(*uintptr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pNew)).FpLeft + 20))
			}
			i = iEq
			for {
				if !(i < libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pLoop)).FnLTerm)) {
					break
				}
				if (*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)))).FpExpr == pX {
					iField = (*(*struct {
						FleftColumn int32
						FiField     int32
					})(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(i)*4)) + 24))).FiField - int32(1)
					if (*(*TExprList_item)(unsafe.Pointer(pOrigRhs + 8 + uintptr(iField)*20))).FpExpr == uintptr(0) {
						goto _2 /* Duplicate PK column */
					}
					pRhs = _sqlite3ExprListAppend(tls, pParse, pRhs, (*(*TExprList_item)(unsafe.Pointer(pOrigRhs + 8 + uintptr(iField)*20))).FpExpr)
					(*(*TExprList_item)(unsafe.Pointer(pOrigRhs + 8 + uintptr(iField)*20))).FpExpr = uintptr(0)
					if pRhs != 0 {
						*(*Tu16)(unsafe.Pointer(pRhs + 8 + uintptr((*TExprList)(unsafe.Pointer(pRhs)).FnExpr-int32(1))*20 + 16)) = libc.Uint16FromInt32(iField + int32(1))
					}
					if pOrigLhs != 0 {
						pLhs = _sqlite3ExprListAppend(tls, pParse, pLhs, (*(*TExprList_item)(unsafe.Pointer(pOrigLhs + 8 + uintptr(iField)*20))).FpExpr)
						(*(*TExprList_item)(unsafe.Pointer(pOrigLhs + 8 + uintptr(iField)*20))).FpExpr = uintptr(0)
					}
				}
				goto _2
			_2:
				;
				i = i + 1
			}
			_sqlite3ExprListDelete(tls, db, pOrigRhs)
			if pOrigLhs != 0 {
				_sqlite3ExprListDelete(tls, db, pOrigLhs)
				*(*uintptr)(unsafe.Pointer((*TExpr)(unsafe.Pointer(pNew)).FpLeft + 20)) = pLhs
			}
			(*TSelect)(unsafe.Pointer(pSelect)).FpEList = pRhs
			v4 = pParse + 100
			*(*int32)(unsafe.Pointer(v4)) = *(*int32)(unsafe.Pointer(v4)) + 1
			v3 = *(*int32)(unsafe.Pointer(v4))
			(*TSelect)(unsafe.Pointer(pSelect)).FselId = libc.Uint32FromInt32(v3) /* Req'd for SubrtnSig validity */
			if pLhs != 0 && (*TExprList)(unsafe.Pointer(pLhs)).FnExpr == int32(1) {
				/* Take care here not to generate a TK_VECTOR containing only a
				 ** single value. Since the parser never creates such a vector, some
				 ** of the subroutines do not handle this case.  */
				p = (*(*TExprList_item)(unsafe.Pointer(pLhs + 8))).FpExpr
				(*(*TExprList_item)(unsafe.Pointer(pLhs + 8))).FpExpr = uintptr(0)
				_sqlite3ExprDelete(tls, db, (*TExpr)(unsafe.Pointer(pNew)).FpLeft)
				(*TExpr)(unsafe.Pointer(pNew)).FpLeft = p
			}
			/* If either the ORDER BY clause or the GROUP BY clause contains
			 ** references to result-set columns, those references might now be
			 ** obsolete.  So fix them up.
			 */
			if pRhs != 0 {
				_adjustOrderByCol(tls, (*TSelect)(unsafe.Pointer(pSelect)).FpOrderBy, pRhs)
				_adjustOrderByCol(tls, (*TSelect)(unsafe.Pointer(pSelect)).FpGroupBy, pRhs)
				i = 0
				for {
					if !(i < (*TExprList)(unsafe.Pointer(pRhs)).FnExpr) {
						break
					}
					*(*Tu16)(unsafe.Pointer(pRhs + 8 + uintptr(i)*20 + 16)) = uint16(0)
					goto _5
				_5:
					;
					i = i + 1
				}
			}
			goto _1
		_1:
			;
			pSelect = (*TSelect)(unsafe.Pointer(pSelect)).FpPrior
		}
	}
	return pNew
}

// C documentation
//
//	/*
//	** This is a Walker expression callback.
//	**
//	** For every TK_COLUMN node in the expression tree, search to see
//	** if the column being references is the column being renamed by an
//	** ALTER TABLE statement.  If it is, then attach its associated
//	** RenameToken object to the list of RenameToken objects being
//	** constructed in RenameCtx object at pWalker->u.pRename.
//	*/
func _renameColumnExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var p uintptr
	_ = p
	p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_TRIGGER) && int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) == (*TRenameCtx)(unsafe.Pointer(p)).FiCol && (*TParse)(unsafe.Pointer((*TWalker)(unsafe.Pointer(pWalker)).FpParse)).FpTriggerTab == (*TRenameCtx)(unsafe.Pointer(p)).FpTab {
		_renameTokenFind(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, p, pExpr)
	} else {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) && int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) == (*TRenameCtx)(unsafe.Pointer(p)).FiCol && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)|libc.Int32FromInt32(EP_Subrtn)) == uint32(0) && (*TRenameCtx)(unsafe.Pointer(p)).FpTab == (*TExpr)(unsafe.Pointer(pExpr)).Fy.FpTab {
			_renameTokenFind(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, p, pExpr)
		}
	}
	return WRC_Continue
}

func _renameQuotefixExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_STRING) && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&uint32(EP_DblQuoted) != 0 {
		_renameTokenFind(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, *(*uintptr)(unsafe.Pointer(pWalker + 24)), pExpr)
	}
	return WRC_Continue
}

// C documentation
//
//	/* SQL function: sqlite_rename_quotefix(DB,SQL)
//	**
//	** Rewrite the DDL statement "SQL" so that any string literals that use
//	** double-quotes use single quotes instead.
//	**
//	** Two arguments must be passed:
//	**
//	**   0: Database name ("main", "temp" etc.).
//	**   1: SQL statement to edit.
//	**
//	** The returned value is the modified SQL statement. For example, given
//	** the database schema:
//	**
//	**   CREATE TABLE t1(a, b, c);
//	**
//	**   SELECT sqlite_rename_quotefix('main',
//	**       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
//	**   );
//	**
//	** returns the string:
//	**
//	**   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
//	**
//	** If there is a error in the input SQL, then raise an error, except
//	** if PRAGMA writable_schema=ON, then just return the input string
//	** unmodified following an error.
//	*/
func _renameQuotefixFunc(tls *libc.TLS, context uintptr, NotUsed int32, argv uintptr) {
	bp := tls.Alloc(336)
	defer tls.Free(336)
	var db, pSelect, zDb, zInput uintptr
	var i, rc, v1 int32
	var xAuth Tsqlite3_xauth
	var _ /* sCtx at bp+284 */ TRenameCtx
	var _ /* sParse at bp+0 */ TParse
	var _ /* sWalker at bp+304 */ TWalker
	_, _, _, _, _, _, _, _ = db, i, pSelect, rc, xAuth, zDb, zInput, v1
	db = Xsqlite3_context_db_handle(tls, context)
	zDb = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
	zInput = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
	xAuth = (*Tsqlite3)(unsafe.Pointer(db)).FxAuth
	(*Tsqlite3)(unsafe.Pointer(db)).FxAuth = uintptr(0)
	_sqlite3BtreeEnterAll(tls, db)
	_ = NotUsed
	if zDb != 0 && zInput != 0 {
		rc = _renameParseSql(tls, bp, zDb, db, zInput, 0)
		if rc == SQLITE_OK {
			/* Walker to find tokens that need to be replaced. */
			libc.Xmemset(tls, bp+284, 0, uint32(20))
			libc.Xmemset(tls, bp+304, 0, uint32(28))
			(**(**TWalker)(__ccgo_up(bp + 304))).FpParse = bp
			(**(**TWalker)(__ccgo_up(bp + 304))).FxExprCallback = __ccgo_fp(_renameQuotefixExprCb)
			(**(**TWalker)(__ccgo_up(bp + 304))).FxSelectCallback = __ccgo_fp(_renameColumnSelectCb)
			*(*uintptr)(unsafe.Pointer(bp + 304 + 24)) = bp + 284
			if (**(**TParse)(__ccgo_up(bp))).FpNewTable != 0 {
				if libc.Int32FromUint8((*TTable)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewTable)).FeTabType) == int32(TABTYP_VIEW) {
					pSelect = (*(*struct {
						FpSelect uintptr
					})(unsafe.Pointer(&(*TTable)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewTable)).Fu))).FpSelect
					**(**Tu32)(__ccgo_up(pSelect + 4)) &= ^libc.Uint32FromInt32(SF_View)
					(**(**TParse)(__ccgo_up(bp))).Frc = SQLITE_OK
					_sqlite3SelectPrep(tls, bp, pSelect, uintptr(0))
					if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
						v1 = int32(SQLITE_NOMEM)
					} else {
						v1 = (**(**TParse)(__ccgo_up(bp))).Frc
					}
					rc = v1
					if rc == SQLITE_OK {
						_sqlite3WalkSelect(tls, bp+304, pSelect)
					}
				} else {
					_sqlite3WalkExprList(tls, bp+304, (*TTable)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewTable)).FpCheck)
					i = 0
					for {
						if !(i < int32((*TTable)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewTable)).FnCol)) {
							break
						}
						_sqlite3WalkExpr(tls, bp+304, _sqlite3ColumnExpr(tls, (**(**TParse)(__ccgo_up(bp))).FpNewTable, (*TTable)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewTable)).FaCol+uintptr(i)*12))
						goto _2
					_2:
						;
						i = i + 1
					}
				}
			} else {
				if (**(**TParse)(__ccgo_up(bp))).FpNewIndex != 0 {
					_sqlite3WalkExprList(tls, bp+304, (*TIndex)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewIndex)).FaColExpr)
					_sqlite3WalkExpr(tls, bp+304, (*TIndex)(unsafe.Pointer((**(**TParse)(__ccgo_up(bp))).FpNewIndex)).FpPartIdxWhere)
				} else {
					rc = _renameResolveTrigger(tls, bp)
					if rc == SQLITE_OK {
						_renameWalkTrigger(tls, bp+304, (**(**TParse)(__ccgo_up(bp))).FpNewTrigger)
					}
				}
			}
			if rc == SQLITE_OK {
				rc = _renameEditSql(tls, context, bp+284, zInput, uintptr(0), 0)
			}
			_renameTokenFree(tls, db, (**(**TRenameCtx)(__ccgo_up(bp + 284))).FpList)
		}
		if rc != SQLITE_OK {
			if _sqlite3WritableSchema(tls, db) != 0 && rc == int32(SQLITE_ERROR) {
				Xsqlite3_result_value(tls, context, **(**uintptr)(__ccgo_up(argv + 1*4)))
			} else {
				Xsqlite3_result_error_code(tls, context, rc)
			}
		}
		_renameParseCleanup(tls, bp)
	}
	(*Tsqlite3)(unsafe.Pointer(db)).FxAuth = xAuth
	_sqlite3BtreeLeaveAll(tls, db)
}

// C documentation
//
//	/*
//	** Set all pEList->a[].fg.eEName fields in the expression-list to val.
//	*/
func _renameSetENames(tls *libc.TLS, pEList uintptr, val int32) {
	var i int32
	_ = i
	if pEList != 0 {
		i = 0
		for {
			if !(i < (*TExprList)(unsafe.Pointer(pEList)).FnExpr) {
				break
			}
			libc.SetBitFieldPtr16Uint32(pEList+8+uintptr(i)*20+8+4, libc.Uint32FromInt32(val&libc.Int32FromInt32(0x3)), 0, 0x3)
			goto _1
		_1:
			;
			i = i + 1
		}
	}
}

// C documentation
//
//	/*
//	** Walker expression callback used by "RENAME TABLE".
//	*/
func _renameTableExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var p uintptr
	_ = p
	p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)|libc.Int32FromInt32(EP_Subrtn)) == uint32(0) && (*TRenameCtx)(unsafe.Pointer(p)).FpTab == (*TExpr)(unsafe.Pointer(pExpr)).Fy.FpTab {
		_renameTokenFind(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, p, pExpr+44)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Walker select callback used by "RENAME TABLE".
//	*/
func _renameTableSelectCb(tls *libc.TLS, pWalker uintptr, pSelect uintptr) (r int32) {
	var i int32
	var p, pItem, pSrc uintptr
	_, _, _, _ = i, p, pItem, pSrc
	p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	pSrc = (*TSelect)(unsafe.Pointer(pSelect)).FpSrc
	if (*TSelect)(unsafe.Pointer(pSelect)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_View)|libc.Int32FromInt32(SF_CopyCte)) != 0 {
		return int32(WRC_Prune)
	}
	if pSrc == uintptr(0) {
		return int32(WRC_Abort)
	}
	i = 0
	for {
		if !(i < (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc) {
			break
		}
		pItem = pSrc + 8 + uintptr(i)*48
		if (*TSrcItem)(unsafe.Pointer(pItem)).FpSTab == (*TRenameCtx)(unsafe.Pointer(p)).FpTab {
			_renameTokenFind(tls, (*TWalker)(unsafe.Pointer(pWalker)).FpParse, p, (*TSrcItem)(unsafe.Pointer(pItem)).FzName)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	_renameWalkWith(tls, pWalker, pSelect)
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Walker callback used by sqlite3RenameExprUnmap().
//	*/
func _renameUnmapExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pParse uintptr
	_ = pParse
	pParse = (*TWalker)(unsafe.Pointer(pWalker)).FpParse
	_sqlite3RenameTokenRemap(tls, pParse, uintptr(0), pExpr)
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)|libc.Int32FromInt32(EP_Subrtn)) == uint32(0) {
		_sqlite3RenameTokenRemap(tls, pParse, uintptr(0), pExpr+44)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Walker callback used by sqlite3RenameExprUnmap().
//	*/
func _renameUnmapSelectCb(tls *libc.TLS, pWalker uintptr, p uintptr) (r int32) {
	var i int32
	var pList, pParse, pSrc uintptr
	_, _, _, _ = i, pList, pParse, pSrc
	pParse = (*TWalker)(unsafe.Pointer(pWalker)).FpParse
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		return int32(WRC_Abort)
	}
	if (*TSelect)(unsafe.Pointer(p)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_View)|libc.Int32FromInt32(SF_CopyCte)) != 0 {
		return int32(WRC_Prune)
	}
	if (*TSelect)(unsafe.Pointer(p)).FpEList != 0 {
		pList = (*TSelect)(unsafe.Pointer(p)).FpEList
		i = 0
		for {
			if !(i < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
				break
			}
			if (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FzEName != 0 && int32(uint32(*(*uint16)(unsafe.Pointer(pList + 8 + uintptr(i)*20 + 8 + 4))&0x3>>0)) == ENAME_NAME {
				_sqlite3RenameTokenRemap(tls, pParse, uintptr(0), (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FzEName)
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	if (*TSelect)(unsafe.Pointer(p)).FpSrc != 0 { /* Every Select as a SrcList, even if it is empty */
		pSrc = (*TSelect)(unsafe.Pointer(p)).FpSrc
		i = 0
		for {
			if !(i < (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc) {
				break
			}
			_sqlite3RenameTokenRemap(tls, pParse, uintptr(0), (*(*TSrcItem)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48))).FzName)
			if int32(*(*uint32)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48 + 12 + 4))&0x800>>11) == 0 {
				_sqlite3WalkExpr(tls, pWalker, *(*uintptr)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48 + 40)))
			} else {
				_unmapColumnIdlistNames(tls, pParse, *(*uintptr)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48 + 40)))
			}
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	_renameWalkWith(tls, pWalker, p)
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Expression walker callback used by renumberCursors() to update
//	** Expr objects to match newly assigned cursor numbers.
//	*/
func _renumberCursorsCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var op int32
	_ = op
	op = libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop)
	if op == int32(TK_COLUMN) || op == int32(TK_IF_NULL_ROW) {
		_renumberCursorDoMapping(tls, pWalker, pExpr+28)
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0) {
		_renumberCursorDoMapping(tls, pWalker, pExpr+36)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Resize an Index object to hold N columns total.  Return SQLITE_OK
//	** on success and SQLITE_NOMEM on an OOM error.
//	*/
func _resizeIndexObject(tls *libc.TLS, pParse uintptr, pIdx uintptr, N int32) (r int32) {
	var db, zExtra uintptr
	var nByte Tu64
	_, _, _ = db, nByte, zExtra
	if libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn) >= N {
		return SQLITE_OK
	}
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	nByte = uint64(libc.Uint32FromInt64(4)+libc.Uint32FromInt64(2)+libc.Uint32FromInt64(2)+libc.Uint32FromInt32(1)) * libc.Uint64FromInt32(N)
	zExtra = _sqlite3DbMallocZero(tls, db, nByte)
	if zExtra == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemcpy(tls, zExtra, (*TIndex)(unsafe.Pointer(pIdx)).FazColl, uint32(4)*uint32((*TIndex)(unsafe.Pointer(pIdx)).FnColumn))
	(*TIndex)(unsafe.Pointer(pIdx)).FazColl = zExtra
	zExtra = zExtra + uintptr(uint32(4)*libc.Uint32FromInt32(N))
	libc.Xmemcpy(tls, zExtra, (*TIndex)(unsafe.Pointer(pIdx)).FaiRowLogEst, uint32(2)*libc.Uint32FromInt32(libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)+libc.Int32FromInt32(1)))
	(*TIndex)(unsafe.Pointer(pIdx)).FaiRowLogEst = zExtra
	zExtra = zExtra + uintptr(uint32(2)*libc.Uint32FromInt32(N))
	libc.Xmemcpy(tls, zExtra, (*TIndex)(unsafe.Pointer(pIdx)).FaiColumn, uint32(2)*uint32((*TIndex)(unsafe.Pointer(pIdx)).FnColumn))
	(*TIndex)(unsafe.Pointer(pIdx)).FaiColumn = zExtra
	zExtra = zExtra + uintptr(uint32(2)*libc.Uint32FromInt32(N))
	libc.Xmemcpy(tls, zExtra, (*TIndex)(unsafe.Pointer(pIdx)).FaSortOrder, uint32((*TIndex)(unsafe.Pointer(pIdx)).FnColumn))
	(*TIndex)(unsafe.Pointer(pIdx)).FaSortOrder = zExtra
	(*TIndex)(unsafe.Pointer(pIdx)).FnColumn = libc.Uint16FromInt32(N) /* See tag-20250221-1 above for proof of safety */
	libc.SetBitFieldPtr16Uint32(pIdx+56, libc.Uint32FromInt32(1), 4, 0x10)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Resolve label "x" to be the address of the next instruction to
//	** be inserted.  The parameter "x" must have been obtained from
//	** a prior call to sqlite3VdbeMakeLabel().
//	*/
func _resizeResolveLabel(tls *libc.TLS, p uintptr, v uintptr, j int32) {
	var nNewSize int32
	_ = nNewSize
	nNewSize = int32(10) - (*TParse)(unsafe.Pointer(p)).FnLabel
	(*TParse)(unsafe.Pointer(p)).FaLabel = _sqlite3DbReallocOrFree(tls, (*TParse)(unsafe.Pointer(p)).Fdb, (*TParse)(unsafe.Pointer(p)).FaLabel, uint64(libc.Uint32FromInt32(nNewSize)*uint32(4)))
	if (*TParse)(unsafe.Pointer(p)).FaLabel == uintptr(0) {
		(*TParse)(unsafe.Pointer(p)).FnLabelAlloc = 0
	} else {
		if nNewSize >= int32(100) && nNewSize/int32(100) > (*TParse)(unsafe.Pointer(p)).FnLabelAlloc/int32(100) {
			_sqlite3ProgressCheck(tls, p)
		}
		(*TParse)(unsafe.Pointer(p)).FnLabelAlloc = nNewSize
		**(**int32)(__ccgo_up((*TParse)(unsafe.Pointer(p)).FaLabel + uintptr(j)*4)) = (*TVdbe)(unsafe.Pointer(v)).FnOp
	}
}

// C documentation
//
//	/*
//	** Turn the pExpr expression into an alias for the iCol-th column of the
//	** result set in pEList.
//	**
//	** If the reference is followed by a COLLATE operator, then make sure
//	** the COLLATE operator is preserved.  For example:
//	**
//	**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
//	**
//	** Should be transformed into:
//	**
//	**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
//	**
//	** The nSubquery parameter specifies how many levels of subquery the
//	** alias is removed from the original expression.  The usual value is
//	** zero but it might be more if the alias is contained within a subquery
//	** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
//	** structures must be increased by the nSubquery amount.
//	*/
func _resolveAlias(tls *libc.TLS, pParse uintptr, pEList uintptr, iCol int32, pExpr uintptr, nSubquery int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var db, pDup, pOrig uintptr
	var _ /* temp at bp+0 */ TExpr
	_, _, _ = db, pDup, pOrig /* The database connection */
	pOrig = (*(*TExprList_item)(unsafe.Pointer(pEList + 8 + uintptr(iCol)*20))).FpExpr
	if (*TExpr)(unsafe.Pointer(pExpr)).FpAggInfo != 0 {
		return
	}
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	pDup = _sqlite3ExprDup(tls, db, pOrig, 0)
	if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
		_sqlite3ExprDelete(tls, db, pDup)
		pDup = uintptr(0)
	} else {
		_incrAggFunctionDepth(tls, pDup, nSubquery)
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLLATE) {
			pDup = _sqlite3ExprAddCollateString(tls, pParse, pDup, *(*uintptr)(unsafe.Pointer(pExpr + 8)))
		}
		libc.Xmemcpy(tls, bp, pDup, uint32(52))
		libc.Xmemcpy(tls, pDup, pExpr, uint32(52))
		libc.Xmemcpy(tls, pExpr, bp, uint32(52))
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
			if *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy)) != uintptr(0) {
				(*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy)))).FpOwner = pExpr
			}
		}
		_sqlite3ExprDeferredDelete(tls, pParse, pDup)
	}
}

// C documentation
//
//	/*
//	** pEList is a list of expressions which are really the result set of the
//	** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
//	** This routine checks to see if pE is a simple identifier which corresponds
//	** to the AS-name of one of the terms of the expression list.  If it is,
//	** this routine return an integer between 1 and N where N is the number of
//	** elements in pEList, corresponding to the matching entry.  If there is
//	** no match, or if pE is not a simple identifier, then this routine
//	** return 0.
//	**
//	** pEList has been resolved.  pE has not.
//	*/
func _resolveAsName(tls *libc.TLS, pParse uintptr, pEList uintptr, pE uintptr) (r int32) {
	var i int32
	var zCol uintptr
	_, _ = i, zCol /* Loop counter */
	_ = pParse
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pE)).Fop) == int32(TK_ID) {
		zCol = *(*uintptr)(unsafe.Pointer(pE + 8))
		i = 0
		for {
			if !(i < (*TExprList)(unsafe.Pointer(pEList)).FnExpr) {
				break
			}
			if int32(uint32(*(*uint16)(unsafe.Pointer(pEList + 8 + uintptr(i)*20 + 8 + 4))&0x3>>0)) == ENAME_NAME && Xsqlite3_stricmp(tls, (*(*TExprList_item)(unsafe.Pointer(pEList + 8 + uintptr(i)*20))).FzEName, zCol) == 0 {
				return i + int32(1)
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** Walker callback for windowRemoveExprFromSelect().
//	*/
func _resolveRemoveWindowsCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var pWin uintptr
	_ = pWin
	_ = pWalker
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
		pWin = *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy))
		_sqlite3WindowUnlinkFromSelect(tls, pWin)
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Set the EP_SubtArg property on every expression inside of
//	** pList.  If any subexpression is actually a subquery, then
//	** also set the EP_SubtArg property on the first result-set
//	** column of that subquery.
//	*/
func _resolveSetExprSubtypeArg(tls *libc.TLS, pList uintptr) {
	var ii, nn, v1 int32
	var pExpr uintptr
	_, _, _, _ = ii, nn, pExpr, v1
	if pList != 0 {
		v1 = (*TExprList)(unsafe.Pointer(pList)).FnExpr
	} else {
		v1 = 0
	}
	nn = v1
	ii = 0
	for {
		if !(ii < nn) {
			break
		}
		pExpr = (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(ii)*20))).FpExpr
		**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromUint32(EP_SubtArg)
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_SELECT) {
			_resolveSetExprSubtypeArg(tls, (*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FpEList)
		}
		goto _2
	_2:
		;
		ii = ii + 1
	}
}

// C documentation
//
//	/*
//	** Rtree virtual table module xColumn method.
//	*/
func _rtreeColumn(tls *libc.TLS, cur uintptr, ctx uintptr, i int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var p, pCsr, pNode, pRtree uintptr
	var _ /* c at bp+0 */ TRtreeCoord
	var _ /* rc at bp+4 */ int32
	_, _, _, _ = p, pCsr, pNode, pRtree
	pRtree = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(cur)).FpVtab
	pCsr = cur
	p = _rtreeSearchPointFirst(tls, pCsr)
	**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
	pNode = _rtreeNodeOfFirstSearchPoint(tls, pCsr, bp+4)
	if **(**int32)(__ccgo_up(bp + 4)) != 0 {
		return **(**int32)(__ccgo_up(bp + 4))
	}
	if p == uintptr(0) {
		return SQLITE_OK
	}
	if libc.Int32FromUint8((*TRtreeSearchPoint)(unsafe.Pointer(p)).FiCell) >= _readInt16(tls, (*TRtreeNode)(unsafe.Pointer(pNode)).FzData+2) {
		return int32(SQLITE_ABORT)
	}
	if i == 0 {
		Xsqlite3_result_int64(tls, ctx, _nodeGetRowid(tls, pRtree, pNode, libc.Int32FromUint8((*TRtreeSearchPoint)(unsafe.Pointer(p)).FiCell)))
	} else {
		if i <= libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim2) {
			_nodeGetCoord(tls, pRtree, pNode, libc.Int32FromUint8((*TRtreeSearchPoint)(unsafe.Pointer(p)).FiCell), i-int32(1), bp)
			if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
				Xsqlite3_result_double(tls, ctx, float64(*(*TRtreeValue)(unsafe.Pointer(bp))))
			} else {
				Xsqlite3_result_int(tls, ctx, *(*int32)(unsafe.Pointer(bp)))
			}
		} else {
			if !((*TRtreeCursor)(unsafe.Pointer(pCsr)).FbAuxValid != 0) {
				if (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux == uintptr(0) {
					**(**int32)(__ccgo_up(bp + 4)) = Xsqlite3_prepare_v3(tls, (*TRtree)(unsafe.Pointer(pRtree)).Fdb, (*TRtree)(unsafe.Pointer(pRtree)).FzReadAuxSql, -int32(1), uint32(0), pCsr+36, uintptr(0))
					if **(**int32)(__ccgo_up(bp + 4)) != 0 {
						return **(**int32)(__ccgo_up(bp + 4))
					}
				}
				Xsqlite3_bind_int64(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux, int32(1), _nodeGetRowid(tls, pRtree, pNode, libc.Int32FromUint8((*TRtreeSearchPoint)(unsafe.Pointer(p)).FiCell)))
				**(**int32)(__ccgo_up(bp + 4)) = Xsqlite3_step(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux)
				if **(**int32)(__ccgo_up(bp + 4)) == int32(SQLITE_ROW) {
					(*TRtreeCursor)(unsafe.Pointer(pCsr)).FbAuxValid = uint8(1)
				} else {
					Xsqlite3_reset(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux)
					if **(**int32)(__ccgo_up(bp + 4)) == int32(SQLITE_DONE) {
						**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
					}
					return **(**int32)(__ccgo_up(bp + 4))
				}
			}
			Xsqlite3_result_value(tls, ctx, Xsqlite3_column_value(tls, (*TRtreeCursor)(unsafe.Pointer(pCsr)).FpReadAux, i-libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim2)+int32(1)))
		}
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** The xUpdate method for rtree module virtual tables.
//	*/
func _rtreeUpdate(tls *libc.TLS, pVtab uintptr, nData int32, aData uintptr, pRowid uintptr) (r int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var bHaveRowid, ii, jj, nn, rc, rc2, steprc int32
	var pRtree, pUp uintptr
	var _ /* cell at bp+0 */ TRtreeCell
	var _ /* pLeaf at bp+48 */ uintptr
	_, _, _, _, _, _, _, _, _ = bHaveRowid, ii, jj, nn, pRtree, pUp, rc, rc2, steprc
	pRtree = pVtab
	rc = SQLITE_OK /* New cell to insert if nData>1 */
	bHaveRowid = 0 /* Set to 1 after new rowid is determined */
	if (*TRtree)(unsafe.Pointer(pRtree)).FnNodeRef != 0 {
		/* Unable to write to the btree while another cursor is reading from it,
		 ** since the write might do a rebalance which would disrupt the read
		 ** cursor. */
		return libc.Int32FromInt32(SQLITE_LOCKED) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
	}
	_rtreeReference(tls, pRtree)
	libc.Xmemset(tls, bp, 0, uint32(48))
	/* Constraint handling. A write operation on an r-tree table may return
	 ** SQLITE_CONSTRAINT for two reasons:
	 **
	 **   1. A duplicate rowid value, or
	 **   2. The supplied data violates the "x2>=x1" constraint.
	 **
	 ** In the first case, if the conflict-handling mode is REPLACE, then
	 ** the conflicting row can be removed before proceeding. In the second
	 ** case, SQLITE_CONSTRAINT must be returned regardless of the
	 ** conflict-handling mode specified by the user.
	 */
	if nData > int32(1) {
		nn = nData - int32(4)
		if nn > libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim2) {
			nn = libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim2)
		}
		/* Populate the cell.aCoord[] array. The first coordinate is aData[3].
		 **
		 ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
		 ** with "column" that are interpreted as table constraints.
		 ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
		 ** This problem was discovered after years of use, so we silently ignore
		 ** these kinds of misdeclared tables to avoid breaking any legacy.
		 */
		if libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FeCoordType) == RTREE_COORD_REAL32 {
			ii = 0
			for {
				if !(ii < nn) {
					break
				}
				*(*TRtreeValue)(unsafe.Pointer(bp + 8 + uintptr(ii)*4)) = _rtreeValueDown(tls, **(**uintptr)(__ccgo_up(aData + uintptr(ii+int32(3))*4)))
				*(*TRtreeValue)(unsafe.Pointer(bp + 8 + uintptr(ii+int32(1))*4)) = _rtreeValueUp(tls, **(**uintptr)(__ccgo_up(aData + uintptr(ii+int32(4))*4)))
				if *(*TRtreeValue)(unsafe.Pointer(bp + 8 + uintptr(ii)*4)) > *(*TRtreeValue)(unsafe.Pointer(bp + 8 + uintptr(ii+int32(1))*4)) {
					rc = _rtreeConstraintError(tls, pRtree, ii+int32(1))
					goto constraint
				}
				goto _1
			_1:
				;
				ii = ii + int32(2)
			}
		} else {
			ii = 0
			for {
				if !(ii < nn) {
					break
				}
				*(*int32)(unsafe.Pointer(bp + 8 + uintptr(ii)*4)) = Xsqlite3_value_int(tls, **(**uintptr)(__ccgo_up(aData + uintptr(ii+int32(3))*4)))
				*(*int32)(unsafe.Pointer(bp + 8 + uintptr(ii+int32(1))*4)) = Xsqlite3_value_int(tls, **(**uintptr)(__ccgo_up(aData + uintptr(ii+int32(4))*4)))
				if *(*int32)(unsafe.Pointer(bp + 8 + uintptr(ii)*4)) > *(*int32)(unsafe.Pointer(bp + 8 + uintptr(ii+int32(1))*4)) {
					rc = _rtreeConstraintError(tls, pRtree, ii+int32(1))
					goto constraint
				}
				goto _2
			_2:
				;
				ii = ii + int32(2)
			}
		}
		/* If a rowid value was supplied, check if it is already present in
		 ** the table. If so, the constraint has failed. */
		if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(aData + 2*4))) != int32(SQLITE_NULL) {
			(**(**TRtreeCell)(__ccgo_up(bp))).FiRowid = Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(aData + 2*4)))
			if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(aData))) == int32(SQLITE_NULL) || Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(aData))) != (**(**TRtreeCell)(__ccgo_up(bp))).FiRowid {
				Xsqlite3_bind_int64(tls, (*TRtree)(unsafe.Pointer(pRtree)).FpReadRowid, int32(1), (**(**TRtreeCell)(__ccgo_up(bp))).FiRowid)
				steprc = Xsqlite3_step(tls, (*TRtree)(unsafe.Pointer(pRtree)).FpReadRowid)
				rc = Xsqlite3_reset(tls, (*TRtree)(unsafe.Pointer(pRtree)).FpReadRowid)
				if int32(SQLITE_ROW) == steprc {
					if Xsqlite3_vtab_on_conflict(tls, (*TRtree)(unsafe.Pointer(pRtree)).Fdb) == int32(SQLITE_REPLACE) {
						rc = _rtreeDeleteRowid(tls, pRtree, (**(**TRtreeCell)(__ccgo_up(bp))).FiRowid)
					} else {
						rc = _rtreeConstraintError(tls, pRtree, 0)
						goto constraint
					}
				}
			}
			bHaveRowid = int32(1)
		}
	}
	/* If aData[0] is not an SQL NULL value, it is the rowid of a
	 ** record to delete from the r-tree table. The following block does
	 ** just that.
	 */
	if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(aData))) != int32(SQLITE_NULL) {
		rc = _rtreeDeleteRowid(tls, pRtree, Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(aData))))
	}
	/* If the aData[] array contains more than one element, elements
	 ** (aData[2]..aData[argc-1]) contain a new record to insert into
	 ** the r-tree structure.
	 */
	if rc == SQLITE_OK && nData > int32(1) {
		/* Insert the new record into the r-tree */
		**(**uintptr)(__ccgo_up(bp + 48)) = uintptr(0)
		/* Figure out the rowid of the new row. */
		if bHaveRowid == 0 {
			rc = _rtreeNewRowid(tls, pRtree, bp)
		}
		**(**Tsqlite_int64)(__ccgo_up(pRowid)) = (**(**TRtreeCell)(__ccgo_up(bp))).FiRowid
		if rc == SQLITE_OK {
			rc = _ChooseLeaf(tls, pRtree, bp, 0, bp+48)
		}
		if rc == SQLITE_OK {
			rc = _rtreeInsertCell(tls, pRtree, **(**uintptr)(__ccgo_up(bp + 48)), bp, 0)
			rc2 = _nodeRelease(tls, pRtree, **(**uintptr)(__ccgo_up(bp + 48)))
			if rc == SQLITE_OK {
				rc = rc2
			}
		}
		if rc == SQLITE_OK && (*TRtree)(unsafe.Pointer(pRtree)).FnAux != 0 {
			pUp = (*TRtree)(unsafe.Pointer(pRtree)).FpWriteAux
			Xsqlite3_bind_int64(tls, pUp, int32(1), **(**Tsqlite_int64)(__ccgo_up(pRowid)))
			jj = 0
			for {
				if !(jj < libc.Int32FromUint16((*TRtree)(unsafe.Pointer(pRtree)).FnAux)) {
					break
				}
				Xsqlite3_bind_value(tls, pUp, jj+int32(2), **(**uintptr)(__ccgo_up(aData + uintptr(libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim2)+int32(3)+jj)*4)))
				goto _3
			_3:
				;
				jj = jj + 1
			}
			Xsqlite3_step(tls, pUp)
			rc = Xsqlite3_reset(tls, pUp)
		}
	}
	goto constraint
constraint:
	;
	_rtreeRelease(tls, pRtree)
	return rc
}

// C documentation
//
//	/* Initialize the BLOB value of a ROWID
//	*/
func _sampleSetRowid(tls *libc.TLS, db uintptr, p uintptr, n int32, pData uintptr) {
	if (*TStatSample)(unsafe.Pointer(p)).FnRowid != 0 {
		_sqlite3DbFree(tls, db, *(*uintptr)(unsafe.Pointer(&(*TStatSample)(unsafe.Pointer(p)).Fu)))
	}
	*(*uintptr)(unsafe.Pointer(&(*TStatSample)(unsafe.Pointer(p)).Fu)) = _sqlite3DbMallocRawNN(tls, db, libc.Uint64FromInt32(n))
	if *(*uintptr)(unsafe.Pointer(&(*TStatSample)(unsafe.Pointer(p)).Fu)) != 0 {
		(*TStatSample)(unsafe.Pointer(p)).FnRowid = libc.Uint32FromInt32(n)
		libc.Xmemcpy(tls, *(*uintptr)(unsafe.Pointer(&(*TStatSample)(unsafe.Pointer(p)).Fu)), pData, libc.Uint32FromInt32(n))
	} else {
		(*TStatSample)(unsafe.Pointer(p)).FnRowid = uint32(0)
	}
}

// C documentation
//
//	/*
//	** The cursor passed as the only argument must point to a valid entry
//	** when this function is called (i.e. have eState==CURSOR_VALID). This
//	** function saves the current cursor key in variables pCur->nKey and
//	** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
//	** code otherwise.
//	**
//	** If the cursor is open on an intkey table, then the integer key
//	** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
//	** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
//	** set to point to a malloced buffer pCur->nKey bytes in size containing
//	** the key.
//	*/
func _saveCursorKey(tls *libc.TLS, pCur uintptr) (r int32) {
	var pKey uintptr
	var rc int32
	_, _ = pKey, rc
	rc = SQLITE_OK
	if (*TBtCursor)(unsafe.Pointer(pCur)).FcurIntKey != 0 {
		/* Only the rowid is required for a table btree */
		(*TBtCursor)(unsafe.Pointer(pCur)).FnKey = _sqlite3BtreeIntegerKey(tls, pCur)
	} else {
		(*TBtCursor)(unsafe.Pointer(pCur)).FnKey = libc.Int64FromUint32(_sqlite3BtreePayloadSize(tls, pCur))
		pKey = _sqlite3Malloc(tls, libc.Uint64FromInt64((*TBtCursor)(unsafe.Pointer(pCur)).FnKey+int64(9)+int64(8)))
		if pKey != 0 {
			rc = _sqlite3BtreePayload(tls, pCur, uint32(0), libc.Uint32FromInt32(int32((*TBtCursor)(unsafe.Pointer(pCur)).FnKey)), pKey)
			if rc == SQLITE_OK {
				libc.Xmemset(tls, pKey+uintptr((*TBtCursor)(unsafe.Pointer(pCur)).FnKey), 0, libc.Uint32FromInt32(libc.Int32FromInt32(9)+libc.Int32FromInt32(8)))
				(*TBtCursor)(unsafe.Pointer(pCur)).FpKey = pKey
			} else {
				Xsqlite3_free(tls, pKey)
			}
		} else {
			rc = int32(SQLITE_NOMEM)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Check schema cookies in all databases.  If any cookie is out
//	** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
//	** make no changes to pParse->rc.
//	*/
func _schemaIsValid(tls *libc.TLS, pParse uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, pBt uintptr
	var iDb, openedTransaction, rc int32
	var _ /* cookie at bp+0 */ int32
	_, _, _, _, _ = db, iDb, openedTransaction, pBt, rc
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	iDb = 0
	for {
		if !(iDb < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
			break
		}
		openedTransaction = 0                                                                     /* True if a transaction is opened */
		pBt = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpBt /* Btree database to read cookie from */
		if pBt == uintptr(0) {
			goto _1
		}
		/* If there is not already a read-only (or read-write) transaction opened
		 ** on the b-tree database, open one now. If a transaction is opened, it
		 ** will be closed immediately after reading the meta-value. */
		if _sqlite3BtreeTxnState(tls, pBt) == SQLITE_TXN_NONE {
			rc = _sqlite3BtreeBeginTrans(tls, pBt, 0, uintptr(0))
			if rc == int32(SQLITE_NOMEM) || rc == libc.Int32FromInt32(SQLITE_IOERR)|libc.Int32FromInt32(12)<<libc.Int32FromInt32(8) {
				_sqlite3OomFault(tls, db)
				(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
			}
			if rc != SQLITE_OK {
				return
			}
			openedTransaction = int32(1)
		}
		/* Read the schema cookie from the database. If it does not match the
		 ** value stored as part of the in-memory schema representation,
		 ** set Parse.rc to SQLITE_SCHEMA. */
		_sqlite3BtreeGetMeta(tls, pBt, int32(BTREE_SCHEMA_VERSION), bp)
		if **(**int32)(__ccgo_up(bp)) != (*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema)).Fschema_cookie {
			if libc.Int32FromUint16((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema)).FschemaFlags)&int32(DB_SchemaLoaded) == int32(DB_SchemaLoaded) {
				(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_SCHEMA)
			}
			_sqlite3ResetOneSchema(tls, db, iDb)
		}
		/* Close the transaction, if one was opened. */
		if openedTransaction != 0 {
			_sqlite3BtreeCommit(tls, pBt)
		}
		goto _1
	_1:
		;
		iDb = iDb + 1
	}
}

// C documentation
//
//	/*
//	** Seek to the offset in id->offset then read cnt bytes into pBuf.
//	** Return the number of bytes actually read.  Update the offset.
//	**
//	** To avoid stomping the errno value on a failed write the lastErrno value
//	** is set before returning.
//	*/
func _seekAndWrite(tls *libc.TLS, id uintptr, offset Ti64, pBuf uintptr, cnt int32) (r int32) {
	return _seekAndWriteFd(tls, (*TunixFile)(unsafe.Pointer(id)).Fh, offset, pBuf, cnt, id+20)
}

// C documentation
//
//	/*
//	** The xSelect callback for the search of invalid ON clause terms.
//	*/
func _selectCheckOnClausesSelect(tls *libc.TLS, pWalker uintptr, pSelect uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pCtx uintptr
	var _ /* sCtx at bp+0 */ TCheckOnCtx
	_ = pCtx
	pCtx = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	if (*TSelect)(unsafe.Pointer(pSelect)).FpSrc == (*TCheckOnCtx)(unsafe.Pointer(pCtx)).FpSrc || (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSelect)).FpSrc)).FnSrc == 0 {
		return WRC_Continue
	} else {
		libc.Xmemset(tls, bp, 0, uint32(16))
		(**(**TCheckOnCtx)(__ccgo_up(bp))).FpSrc = (*TSelect)(unsafe.Pointer(pSelect)).FpSrc
		(**(**TCheckOnCtx)(__ccgo_up(bp))).FpParent = pCtx
		*(*uintptr)(unsafe.Pointer(pWalker + 24)) = bp
		_sqlite3WalkSelect(tls, pWalker, pSelect)
		*(*uintptr)(unsafe.Pointer(pWalker + 24)) = pCtx
		**(**Tu32)(__ccgo_up(pSelect + 4)) &= libc.Uint32FromInt32(^libc.Int32FromInt32(SF_OnToWhere))
		return int32(WRC_Prune)
	}
	return r
}

// C documentation
//
//	/*
//	** Walker SELECT callbacks for sqlite3ReferencesSrcList().
//	**
//	** When entering a new subquery on the pExpr argument, add all FROM clause
//	** entries for that subquery to the exclude list.
//	**
//	** When leaving the subquery, remove those entries from the exclude list.
//	*/
func _selectRefEnter(tls *libc.TLS, pWalker uintptr, pSelect uintptr) (r int32) {
	var i, j Ti64
	var p, pSrc, piNew uintptr
	_, _, _, _, _ = i, j, p, pSrc, piNew
	p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	pSrc = (*TSelect)(unsafe.Pointer(pSelect)).FpSrc
	if (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc == 0 {
		return WRC_Continue
	}
	j = (*TRefSrcList)(unsafe.Pointer(p)).FnExclude
	**(**Ti64)(__ccgo_up(p + 8)) += int64((*TSrcList)(unsafe.Pointer(pSrc)).FnSrc)
	piNew = _sqlite3DbRealloc(tls, (*TRefSrcList)(unsafe.Pointer(p)).Fdb, (*TRefSrcList)(unsafe.Pointer(p)).FaiExclude, libc.Uint64FromInt64((*TRefSrcList)(unsafe.Pointer(p)).FnExclude*int64(4)))
	if piNew == uintptr(0) {
		(*TRefSrcList)(unsafe.Pointer(p)).FnExclude = 0
		return int32(WRC_Abort)
	} else {
		(*TRefSrcList)(unsafe.Pointer(p)).FaiExclude = piNew
	}
	i = 0
	for {
		if !(i < int64((*TSrcList)(unsafe.Pointer(pSrc)).FnSrc)) {
			break
		}
		**(**int32)(__ccgo_up((*TRefSrcList)(unsafe.Pointer(p)).FaiExclude + uintptr(j)*4)) = (*(*TSrcItem)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48))).FiCursor
		goto _1
	_1:
		;
		i = i + 1
		j = j + 1
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Callback function used by selectWindowRewriteEList(). If necessary,
//	** this function appends to the output expression-list and updates
//	** expression (*ppExpr) in place.
//	*/
func _selectWindowRewriteExprCb(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var f, i, i1, iCol, nSrc, v4 int32
	var p, pDup, pParse, pWin uintptr
	_, _, _, _, _, _, _, _, _, _ = f, i, i1, iCol, nSrc, p, pDup, pParse, pWin, v4
	p = *(*uintptr)(unsafe.Pointer(pWalker + 24))
	pParse = (*TWalker)(unsafe.Pointer(pWalker)).FpParse
	/* If this function is being called from within a scalar sub-select
	 ** that used by the SELECT statement being processed, only process
	 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
	 ** not process aggregates or window functions at all, as they belong
	 ** to the scalar sub-select.  */
	if (*TWindowRewrite)(unsafe.Pointer(p)).FpSubSelect != 0 {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_COLUMN) {
			return WRC_Continue
		} else {
			nSrc = (*TSrcList)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpSrc)).FnSrc
			i = 0
			for {
				if !(i < nSrc) {
					break
				}
				if (*TExpr)(unsafe.Pointer(pExpr)).FiTable == (*(*TSrcItem)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpSrc + 8 + uintptr(i)*48))).FiCursor {
					break
				}
				goto _1
			_1:
				;
				i = i + 1
			}
			if i == nSrc {
				return WRC_Continue
			}
		}
	}
	switch libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) {
	case int32(TK_FUNCTION):
		if !((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != libc.Uint32FromInt32(0)) {
			break
		} else {
			pWin = (*TWindowRewrite)(unsafe.Pointer(p)).FpWin
			for {
				if !(pWin != 0) {
					break
				}
				if *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy)) == pWin {
					return int32(WRC_Prune)
				}
				goto _2
			_2:
				;
				pWin = (*TWindow)(unsafe.Pointer(pWin)).FpNextWin
			}
		}
		fallthrough
	case int32(TK_IF_NULL_ROW):
		fallthrough
	case int32(TK_AGG_FUNCTION):
		fallthrough
	case int32(TK_COLUMN):
		iCol = -int32(1)
		if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
			return int32(WRC_Abort)
		}
		if (*TWindowRewrite)(unsafe.Pointer(p)).FpSub != 0 {
			i1 = 0
			for {
				if !(i1 < (*TExprList)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpSub)).FnExpr) {
					break
				}
				if 0 == _sqlite3ExprCompare(tls, uintptr(0), (*(*TExprList_item)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpSub + 8 + uintptr(i1)*20))).FpExpr, pExpr, -int32(1)) {
					iCol = i1
					break
				}
				goto _3
			_3:
				;
				i1 = i1 + 1
			}
		}
		if iCol < 0 {
			pDup = _sqlite3ExprDup(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pExpr, 0)
			if pDup != 0 && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pDup)).Fop) == int32(TK_AGG_FUNCTION) {
				(*TExpr)(unsafe.Pointer(pDup)).Fop = uint8(TK_FUNCTION)
			}
			(*TWindowRewrite)(unsafe.Pointer(p)).FpSub = _sqlite3ExprListAppend(tls, pParse, (*TWindowRewrite)(unsafe.Pointer(p)).FpSub, pDup)
		}
		if (*TWindowRewrite)(unsafe.Pointer(p)).FpSub != 0 {
			f = libc.Int32FromUint32((*TExpr)(unsafe.Pointer(pExpr)).Fflags & uint32(EP_Collate))
			**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_Static))
			_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pExpr)
			**(**Tu32)(__ccgo_up(pExpr + 4)) &= ^libc.Uint32FromInt32(libc.Int32FromInt32(EP_Static))
			libc.Xmemset(tls, pExpr, 0, uint32(52))
			(*TExpr)(unsafe.Pointer(pExpr)).Fop = uint8(TK_COLUMN)
			if iCol < 0 {
				v4 = (*TExprList)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpSub)).FnExpr - int32(1)
			} else {
				v4 = iCol
			}
			(*TExpr)(unsafe.Pointer(pExpr)).FiColumn = int16(v4)
			(*TExpr)(unsafe.Pointer(pExpr)).FiTable = (*TWindow)(unsafe.Pointer((*TWindowRewrite)(unsafe.Pointer(p)).FpWin)).FiEphCsr
			(*TExpr)(unsafe.Pointer(pExpr)).Fy.FpTab = (*TWindowRewrite)(unsafe.Pointer(p)).FpTab
			(*TExpr)(unsafe.Pointer(pExpr)).Fflags = libc.Uint32FromInt32(f)
		}
		if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
			return int32(WRC_Abort)
		}
	default: /* no-op */
		break
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Deserialize the data blob pointed to by buf as serial type serial_type
//	** and store the result in pMem.
//	**
//	** This function is implemented as two separate routines for performance.
//	** The few cases that require local variables are broken out into a separate
//	** routine so that in most cases the overhead of moving the stack pointer
//	** is avoided.
//	*/
func _serialGet(tls *libc.TLS, buf uintptr, serial_type Tu32, pMem uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var y Tu32
	var v1 int32
	var _ /* x at bp+0 */ Tu64
	_, _ = y, v1
	**(**Tu64)(__ccgo_up(bp)) = uint64(uint32(**(**uint8)(__ccgo_up(buf)))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**uint8)(__ccgo_up(buf + 3))))
	y = uint32(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4))))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 3)))
	**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(32) + uint64(y)
	if serial_type == uint32(6) {
		/* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
		 ** twos-complement integer. */
		*(*Ti64)(unsafe.Pointer(pMem)) = **(**Ti64)(__ccgo_up(bp))
		(*TMem)(unsafe.Pointer(pMem)).Fflags = uint16(MEM_Int)
	} else {
		/* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
		 ** floating point number. */
		libc.Xmemcpy(tls, pMem, bp, uint32(8))
		if **(**Tu64)(__ccgo_up(bp))&(libc.Uint64FromInt32(0x7ff)<<libc.Int32FromInt32(52)) == libc.Uint64FromInt32(0x7ff)<<libc.Int32FromInt32(52) && **(**Tu64)(__ccgo_up(bp))&(libc.Uint64FromInt32(1)<<libc.Int32FromInt32(52)-libc.Uint64FromInt32(1)) != uint64(0) {
			v1 = int32(MEM_Null)
		} else {
			v1 = int32(MEM_Real)
		}
		(*TMem)(unsafe.Pointer(pMem)).Fflags = libc.Uint16FromInt32(v1)
	}
}

func _serialGet7(tls *libc.TLS, buf uintptr, pMem uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var y Tu32
	var _ /* x at bp+0 */ Tu64
	_ = y
	**(**Tu64)(__ccgo_up(bp)) = uint64(uint32(**(**uint8)(__ccgo_up(buf)))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**uint8)(__ccgo_up(buf + 3))))
	y = uint32(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4))))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**uint8)(__ccgo_up(buf + libc.UintptrFromInt32(4) + 3)))
	**(**Tu64)(__ccgo_up(bp)) = **(**Tu64)(__ccgo_up(bp))<<libc.Int32FromInt32(32) + uint64(y)
	libc.Xmemcpy(tls, pMem, bp, uint32(8))
	if **(**Tu64)(__ccgo_up(bp))&(libc.Uint64FromInt32(0x7ff)<<libc.Int32FromInt32(52)) == libc.Uint64FromInt32(0x7ff)<<libc.Int32FromInt32(52) && **(**Tu64)(__ccgo_up(bp))&(libc.Uint64FromInt32(1)<<libc.Int32FromInt32(52)-libc.Uint64FromInt32(1)) != uint64(0) {
		(*TMem)(unsafe.Pointer(pMem)).Fflags = uint16(MEM_Null)
		return int32(1)
	}
	(*TMem)(unsafe.Pointer(pMem)).Fflags = uint16(MEM_Real)
	return 0
}

// C documentation
//
//	/*
//	** This function is a no-op if *pRc is other than SQLITE_OK when it is
//	** called. Otherwise, append a blob of data to the buffer.
//	**
//	** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
//	** returning.
//	*/
func _sessionAppendBlob(tls *libc.TLS, p uintptr, aBlob uintptr, nBlob int32, pRc uintptr) {
	if nBlob > 0 && 0 == _sessionBufferGrow(tls, p, int64(nBlob), pRc) {
		libc.Xmemcpy(tls, (*TSessionBuffer)(unsafe.Pointer(p)).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(p)).FnBuf), aBlob, libc.Uint32FromInt32(nBlob))
		**(**int32)(__ccgo_up(p + 4)) += nBlob
	}
}

// C documentation
//
//	/*
//	** Append a DELETE change to the buffer passed as the first argument. Use
//	** the changeset format if argument bPatchset is zero, or the patchset
//	** format otherwise.
//	*/
func _sessionAppendDelete(tls *libc.TLS, pBuf uintptr, bPatchset int32, p uintptr, nCol int32, abPK uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a, pStart, v2 uintptr
	var eType, i int32
	var _ /* n at bp+4 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _ = a, eType, i, pStart, v2
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	_sessionAppendByte(tls, pBuf, uint8(SQLITE_DELETE), bp)
	_sessionAppendByte(tls, pBuf, (*TSessionChange)(unsafe.Pointer(p)).FbIndirect, bp)
	if bPatchset == 0 {
		_sessionAppendBlob(tls, pBuf, (*TSessionChange)(unsafe.Pointer(p)).FaRecord, (*TSessionChange)(unsafe.Pointer(p)).FnRecord, bp)
	} else {
		a = (*TSessionChange)(unsafe.Pointer(p)).FaRecord
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			pStart = a
			v2 = a
			a = a + 1
			eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v2)))
			switch eType {
			case 0:
				fallthrough
			case int32(SQLITE_NULL):
			case int32(SQLITE_FLOAT):
				fallthrough
			case int32(SQLITE_INTEGER):
				a = a + uintptr(8)
			default:
				a = a + uintptr(_sessionVarintGet(tls, a, bp+4))
				a = a + uintptr(**(**int32)(__ccgo_up(bp + 4)))
				break
			}
			if **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				_sessionAppendBlob(tls, pBuf, pStart, int32(a)-int32(pStart), bp)
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** This function is called when rebasing a local UPDATE change against one
//	** or more remote UPDATE changes. The aRec/nRec buffer contains the current
//	** old.* and new.* records for the change. The rebase buffer (a single
//	** record) is in aChange/nChange. The rebased change is appended to buffer
//	** pBuf.
//	**
//	** Rebasing the UPDATE involves:
//	**
//	**   * Removing any changes to fields for which the corresponding field
//	**     in the rebase buffer is set to "replaced" (type 0xFF). If this
//	**     means the UPDATE change updates no fields, nothing is appended
//	**     to the output buffer.
//	**
//	**   * For each field modified by the local change for which the
//	**     corresponding field in the rebase buffer is not "undefined" (0x00)
//	**     or "replaced" (0xFF), the old.* value is replaced by the value
//	**     in the rebase buffer.
//	*/
func _sessionAppendPartialUpdate(tls *libc.TLS, pBuf uintptr, pIter uintptr, aRec uintptr, nRec int32, aChange uintptr, nChange int32, pRc uintptr) {
	var a1, a2, pOut, v1 uintptr
	var bData, i, n1, n11, n2, n21 int32
	_, _, _, _, _, _, _, _, _, _ = a1, a2, bData, i, n1, n11, n2, n21, pOut, v1
	_sessionBufferGrow(tls, pBuf, libc.Int64FromInt32(2)+int64(nRec)+int64(nChange), pRc)
	if **(**int32)(__ccgo_up(pRc)) == SQLITE_OK {
		bData = 0
		pOut = (*TSessionBuffer)(unsafe.Pointer(pBuf)).FaBuf + uintptr((*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf)
		a1 = aRec
		a2 = aChange
		v1 = pOut
		pOut = pOut + 1
		**(**Tu8)(__ccgo_up(v1)) = uint8(SQLITE_UPDATE)
		v1 = pOut
		pOut = pOut + 1
		**(**Tu8)(__ccgo_up(v1)) = libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbIndirect)
		i = 0
		for {
			if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol) {
				break
			}
			n1 = _sessionSerialLen(tls, a1)
			n2 = _sessionSerialLen(tls, a2)
			if **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FabPK + uintptr(i))) != 0 || libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a2))) == 0 {
				if !(**(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FabPK + uintptr(i))) != 0) && **(**Tu8)(__ccgo_up(a1)) != 0 {
					bData = int32(1)
				}
				libc.Xmemcpy(tls, pOut, a1, libc.Uint32FromInt32(n1))
				pOut = pOut + uintptr(n1)
			} else {
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a2))) != int32(0xFF) && **(**Tu8)(__ccgo_up(a1)) != 0 {
					bData = int32(1)
					libc.Xmemcpy(tls, pOut, a2, libc.Uint32FromInt32(n2))
					pOut = pOut + uintptr(n2)
				} else {
					v1 = pOut
					pOut = pOut + 1
					**(**Tu8)(__ccgo_up(v1)) = uint8('\000')
				}
			}
			a1 = a1 + uintptr(n1)
			a2 = a2 + uintptr(n2)
			goto _3
		_3:
			;
			i = i + 1
		}
		if bData != 0 {
			a2 = aChange
			i = 0
			for {
				if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol) {
					break
				}
				n11 = _sessionSerialLen(tls, a1)
				n21 = _sessionSerialLen(tls, a2)
				if **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FabPK + uintptr(i))) != 0 || libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a2))) != int32(0xFF) {
					libc.Xmemcpy(tls, pOut, a1, libc.Uint32FromInt32(n11))
					pOut = pOut + uintptr(n11)
				} else {
					v1 = pOut
					pOut = pOut + 1
					**(**Tu8)(__ccgo_up(v1)) = uint8('\000')
				}
				a1 = a1 + uintptr(n11)
				a2 = a2 + uintptr(n21)
				goto _5
			_5:
				;
				i = i + 1
			}
			(*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf = int32(pOut) - int32((*TSessionBuffer)(unsafe.Pointer(pBuf)).FaBuf)
		}
	}
}

// C documentation
//
//	/*
//	** Buffers a1 and a2 must both contain a sessions module record nCol
//	** fields in size. This function appends an nCol sessions module
//	** record to buffer pBuf that is a copy of a1, except that for
//	** each field that is undefined in a1[], swap in the field from a2[].
//	*/
func _sessionAppendRecordMerge(tls *libc.TLS, pBuf uintptr, nCol int32, a1 uintptr, n1 int32, a2 uintptr, n2 int32, pRc uintptr) {
	var a1Eof, a2Eof, pOut uintptr
	var i, nn1, nn2, v2, v3 int32
	_, _, _, _, _, _, _, _ = a1Eof, a2Eof, i, nn1, nn2, pOut, v2, v3
	a1Eof = a1 + uintptr(n1)
	a2Eof = a2 + uintptr(n2)
	_sessionBufferGrow(tls, pBuf, int64(n1)+int64(n2), pRc)
	if **(**int32)(__ccgo_up(pRc)) == SQLITE_OK {
		pOut = (*TSessionBuffer)(unsafe.Pointer(pBuf)).FaBuf + uintptr((*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf)
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			if a1 < a1Eof {
				v2 = _sessionSerialLen(tls, a1)
			} else {
				v2 = 0
			}
			nn1 = v2
			if a2 < a2Eof {
				v3 = _sessionSerialLen(tls, a2)
			} else {
				v3 = 0
			}
			nn2 = v3
			if nn1 == 0 || nn2 > 0 && (libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a1))) == 0 || libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a1))) == int32(0xFF)) {
				libc.Xmemcpy(tls, pOut, a2, libc.Uint32FromInt32(nn2))
				pOut = pOut + uintptr(nn2)
			} else {
				libc.Xmemcpy(tls, pOut, a1, libc.Uint32FromInt32(nn1))
				pOut = pOut + uintptr(nn1)
			}
			a1 = a1 + uintptr(nn1)
			a2 = a2 + uintptr(nn2)
			goto _1
		_1:
			;
			i = i + 1
		}
		(*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf = int32(pOut) - int32((*TSessionBuffer)(unsafe.Pointer(pBuf)).FaBuf)
	}
}

// C documentation
//
//	/*
//	** This function is a no-op if *pRc is other than SQLITE_OK when it is
//	** called. Otherwise, append a string to the buffer. All bytes in the string
//	** up to (but not including) the nul-terminator are written to the buffer.
//	**
//	** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
//	** returning.
//	*/
func _sessionAppendStr(tls *libc.TLS, p uintptr, zStr uintptr, pRc uintptr) {
	var nStr int32
	_ = nStr
	nStr = _sqlite3Strlen30(tls, zStr)
	if 0 == _sessionBufferGrow(tls, p, int64(nStr)+int64(1), pRc) {
		libc.Xmemcpy(tls, (*TSessionBuffer)(unsafe.Pointer(p)).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(p)).FnBuf), zStr, libc.Uint32FromInt32(nStr))
		**(**int32)(__ccgo_up(p + 4)) += nStr
		**(**Tu8)(__ccgo_up((*TSessionBuffer)(unsafe.Pointer(p)).FaBuf + uintptr((*TSessionBuffer)(unsafe.Pointer(p)).FnBuf))) = uint8(0x00)
	}
}

// C documentation
//
//	/*
//	** This function is a no-op if *pRc is set to other than SQLITE_OK when it
//	** is called. Otherwise, append a serialized table header (part of the binary
//	** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
//	** SQLite error code before returning.
//	*/
func _sessionAppendTableHdr(tls *libc.TLS, pBuf uintptr, bPatchset int32, pTab uintptr, pRc uintptr) {
	var v1 int32
	_ = v1
	/* Write a table header */
	if bPatchset != 0 {
		v1 = int32('P')
	} else {
		v1 = int32('T')
	}
	_sessionAppendByte(tls, pBuf, libc.Uint8FromInt32(v1), pRc)
	_sessionAppendVarint(tls, pBuf, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol, pRc)
	_sessionAppendBlob(tls, pBuf, (*TSessionTable)(unsafe.Pointer(pTab)).FabPK, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol, pRc)
	_sessionAppendBlob(tls, pBuf, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, libc.Int32FromUint32(libc.Xstrlen(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName))+int32(1), pRc)
}

// C documentation
//
//	/*
//	**
//	** This function appends an update change to the buffer (see the comments
//	** under "CHANGESET FORMAT" at the top of the file). An update change
//	** consists of:
//	**
//	**   1 byte:  SQLITE_UPDATE (0x17)
//	**   n bytes: old.* record (see RECORD FORMAT)
//	**   m bytes: new.* record (see RECORD FORMAT)
//	**
//	** The SessionChange object passed as the third argument contains the
//	** values that were stored in the row when the session began (the old.*
//	** values). The statement handle passed as the second argument points
//	** at the current version of the row (the new.* values).
//	**
//	** If all of the old.* values are equal to their corresponding new.* value
//	** (i.e. nothing has changed), then no data at all is appended to the buffer.
//	**
//	** Otherwise, the old.* record contains all primary key values and the
//	** original values of any fields that have been modified. The new.* record
//	** contains the new values of only those fields that have been modified.
//	*/
func _sessionAppendUpdate(tls *libc.TLS, pBuf uintptr, bPatchset int32, pStmt uintptr, p uintptr, abPK uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var bChanged, bNoop, eType, i, nAdvance, nHdr, nRewind int32
	var pCsr uintptr
	var _ /* buf2 at bp+4 */ TSessionBuffer
	var _ /* dVal at bp+24 */ float64
	var _ /* iVal at bp+16 */ Tsqlite3_int64
	var _ /* n at bp+32 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _ = bChanged, bNoop, eType, i, nAdvance, nHdr, nRewind, pCsr
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	**(**TSessionBuffer)(__ccgo_up(bp + 4)) = TSessionBuffer{} /* Buffer to accumulate new.* record in */
	bNoop = int32(1)                                           /* Set to zero if any values are modified */
	nRewind = (*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf    /* Used to iterate through columns */
	pCsr = (*TSessionChange)(unsafe.Pointer(p)).FaRecord       /* Used to iterate through old.* values */
	_sessionAppendByte(tls, pBuf, uint8(SQLITE_UPDATE), bp)
	_sessionAppendByte(tls, pBuf, (*TSessionChange)(unsafe.Pointer(p)).FbIndirect, bp)
	i = 0
	for {
		if !(i < Xsqlite3_column_count(tls, pStmt)) {
			break
		}
		bChanged = 0
		eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pCsr)))
		switch eType {
		case int32(SQLITE_NULL):
			nAdvance = int32(1)
			if Xsqlite3_column_type(tls, pStmt, i) != int32(SQLITE_NULL) {
				bChanged = int32(1)
			}
		case int32(SQLITE_FLOAT):
			fallthrough
		case int32(SQLITE_INTEGER):
			nAdvance = int32(9)
			if eType == Xsqlite3_column_type(tls, pStmt, i) {
				**(**Tsqlite3_int64)(__ccgo_up(bp + 16)) = _sessionGetI64(tls, pCsr+1)
				if eType == int32(SQLITE_INTEGER) {
					if **(**Tsqlite3_int64)(__ccgo_up(bp + 16)) == Xsqlite3_column_int64(tls, pStmt, i) {
						break
					}
				} else {
					libc.Xmemcpy(tls, bp+24, bp+16, uint32(8))
					if **(**float64)(__ccgo_up(bp + 24)) == Xsqlite3_column_double(tls, pStmt, i) {
						break
					}
				}
			}
			bChanged = int32(1)
		default:
			nHdr = int32(1) + _sessionVarintGet(tls, pCsr+1, bp+32)
			nAdvance = nHdr + **(**int32)(__ccgo_up(bp + 32))
			if eType == Xsqlite3_column_type(tls, pStmt, i) && **(**int32)(__ccgo_up(bp + 32)) == Xsqlite3_column_bytes(tls, pStmt, i) && (**(**int32)(__ccgo_up(bp + 32)) == 0 || 0 == libc.Xmemcmp(tls, pCsr+uintptr(nHdr), Xsqlite3_column_blob(tls, pStmt, i), libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 32))))) {
				break
			}
			bChanged = int32(1)
		}
		/* If at least one field has been modified, this is not a no-op. */
		if bChanged != 0 {
			bNoop = 0
		}
		/* Add a field to the old.* record. This is omitted if this module is
		 ** currently generating a patchset. */
		if bPatchset == 0 {
			if bChanged != 0 || **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				_sessionAppendBlob(tls, pBuf, pCsr, nAdvance, bp)
			} else {
				_sessionAppendByte(tls, pBuf, uint8(0), bp)
			}
		}
		/* Add a field to the new.* record. Or the only record if currently
		 ** generating a patchset.  */
		if bChanged != 0 || bPatchset != 0 && **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
			_sessionAppendCol(tls, bp+4, pStmt, i, bp)
		} else {
			_sessionAppendByte(tls, bp+4, uint8(0), bp)
		}
		pCsr = pCsr + uintptr(nAdvance)
		goto _1
	_1:
		;
		i = i + 1
	}
	if bNoop != 0 {
		(*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf = nRewind
	} else {
		_sessionAppendBlob(tls, pBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf, bp)
	}
	Xsqlite3_free(tls, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf)
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Arguments aLeft and aRight are pointers to change records for table pTab.
//	** This function returns true if the two records apply to the same row (i.e.
//	** have the same values stored in the primary key columns), or false
//	** otherwise.
//	*/
func _sessionChangeEqual(tls *libc.TLS, pTab uintptr, bLeftPkOnly int32, aLeft uintptr, bRightPkOnly int32, aRight uintptr) (r int32) {
	var a1, a2 uintptr
	var iCol, n1, n2 int32
	_, _, _, _, _ = a1, a2, iCol, n1, n2
	a1 = aLeft  /* Cursor to iterate through aLeft */
	a2 = aRight /* Used to iterate through table columns */
	iCol = 0
	for {
		if !(iCol < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
			break
		}
		if **(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(iCol))) != 0 {
			n1 = _sessionSerialLen(tls, a1)
			n2 = _sessionSerialLen(tls, a2)
			if n1 != n2 || libc.Xmemcmp(tls, a1, a2, libc.Uint32FromInt32(n1)) != 0 {
				return 0
			}
			a1 = a1 + uintptr(n1)
			a2 = a2 + uintptr(n2)
		} else {
			if bLeftPkOnly == 0 {
				a1 = a1 + uintptr(_sessionSerialLen(tls, a1))
			}
			if bRightPkOnly == 0 {
				a2 = a2 + uintptr(_sessionSerialLen(tls, a2))
			}
		}
		goto _1
	_1:
		;
		iCol = iCol + 1
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** This function is called to merge two changes to the same row together as
//	** part of an sqlite3changeset_concat() operation. A new change object is
//	** allocated and a pointer to it stored in *ppNew.
//	**
//	** Because they have been vetted by sqlite3changegroup_add() or similar,
//	** both the aRec[] change and the pExist change are safe to use without
//	** checking for buffer overflows.
//	*/
func _sessionChangeMerge(tls *libc.TLS, pTab uintptr, bRebase int32, bPatchset int32, pExist uintptr, op2 int32, bIndirect int32, aRec uintptr, nRec int32, ppNew uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a1, a2, aExist, pIn, pNew, pOut, pOut1, v2 uintptr
	var i, i1, n1, n2, nIn, op1, rc int32
	var nByte, nByte1 Tsqlite3_int64
	var _ /* a1 at bp+4 */ uintptr
	var _ /* a1 at bp+8 */ uintptr
	var _ /* a2 at bp+12 */ uintptr
	var _ /* aCsr at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = a1, a2, aExist, i, i1, n1, n2, nByte, nByte1, nIn, op1, pIn, pNew, pOut, pOut1, rc, v2
	pNew = uintptr(0)
	rc = SQLITE_OK
	if !(pExist != 0) {
		pNew = Xsqlite3_malloc64(tls, uint64(uint32(20)+libc.Uint32FromInt32(nRec)))
		if !(pNew != 0) {
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, pNew, 0, uint32(20))
		(*TSessionChange)(unsafe.Pointer(pNew)).Fop = libc.Uint8FromInt32(op2)
		(*TSessionChange)(unsafe.Pointer(pNew)).FbIndirect = libc.Uint8FromInt32(bIndirect)
		(*TSessionChange)(unsafe.Pointer(pNew)).FaRecord = pNew + 1*20
		if bIndirect == 0 || bRebase == 0 {
			(*TSessionChange)(unsafe.Pointer(pNew)).FnRecord = nRec
			libc.Xmemcpy(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord, aRec, libc.Uint32FromInt32(nRec))
		} else {
			pIn = aRec
			pOut = (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord
			i = 0
			for {
				if !(i < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
					break
				}
				nIn = _sessionSerialLen(tls, pIn)
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pIn))) == 0 {
					v2 = pOut
					pOut = pOut + 1
					**(**Tu8)(__ccgo_up(v2)) = uint8(0)
				} else {
					if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i)))) == 0 {
						v2 = pOut
						pOut = pOut + 1
						**(**Tu8)(__ccgo_up(v2)) = uint8(0xFF)
					} else {
						libc.Xmemcpy(tls, pOut, pIn, libc.Uint32FromInt32(nIn))
						pOut = pOut + uintptr(nIn)
					}
				}
				pIn = pIn + uintptr(nIn)
				goto _1
			_1:
				;
				i = i + 1
			}
			(*TSessionChange)(unsafe.Pointer(pNew)).FnRecord = int32(pOut) - int32((*TSessionChange)(unsafe.Pointer(pNew)).FaRecord)
		}
	} else {
		if bRebase != 0 {
			if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pExist)).Fop) == int32(SQLITE_DELETE) && (*TSessionChange)(unsafe.Pointer(pExist)).FbIndirect != 0 {
				**(**uintptr)(__ccgo_up(ppNew)) = pExist
			} else {
				nByte = libc.Int64FromUint32(libc.Uint32FromInt32(nRec+(*TSessionChange)(unsafe.Pointer(pExist)).FnRecord) + uint32(20))
				pNew = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
				if pNew == uintptr(0) {
					rc = int32(SQLITE_NOMEM)
				} else {
					a1 = (*TSessionChange)(unsafe.Pointer(pExist)).FaRecord
					a2 = aRec
					libc.Xmemset(tls, pNew, 0, libc.Uint32FromInt64(nByte))
					(*TSessionChange)(unsafe.Pointer(pNew)).FbIndirect = libc.BoolUint8(bIndirect != 0 || (*TSessionChange)(unsafe.Pointer(pExist)).FbIndirect != 0)
					(*TSessionChange)(unsafe.Pointer(pNew)).Fop = libc.Uint8FromInt32(op2)
					v2 = pNew + 1*20
					(*TSessionChange)(unsafe.Pointer(pNew)).FaRecord = v2
					pOut1 = v2
					i1 = 0
					for {
						if !(i1 < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
							break
						}
						n1 = _sessionSerialLen(tls, a1)
						n2 = _sessionSerialLen(tls, a2)
						if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a1))) == int32(0xFF) || libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i1)))) == 0 && bIndirect != 0 {
							v2 = pOut1
							pOut1 = pOut1 + 1
							**(**Tu8)(__ccgo_up(v2)) = uint8(0xFF)
						} else {
							if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a2))) == 0 {
								libc.Xmemcpy(tls, pOut1, a1, libc.Uint32FromInt32(n1))
								pOut1 = pOut1 + uintptr(n1)
							} else {
								libc.Xmemcpy(tls, pOut1, a2, libc.Uint32FromInt32(n2))
								pOut1 = pOut1 + uintptr(n2)
							}
						}
						a1 = a1 + uintptr(n1)
						a2 = a2 + uintptr(n2)
						goto _5
					_5:
						;
						i1 = i1 + 1
					}
					(*TSessionChange)(unsafe.Pointer(pNew)).FnRecord = int32(pOut1) - int32((*TSessionChange)(unsafe.Pointer(pNew)).FaRecord)
				}
				Xsqlite3_free(tls, pExist)
			}
		} else {
			op1 = libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pExist)).Fop)
			/*
			 **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
			 **   op1=INSERT, op2=UPDATE      ->      INSERT.
			 **   op1=INSERT, op2=DELETE      ->      (none)
			 **
			 **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
			 **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
			 **   op1=UPDATE, op2=DELETE      ->      DELETE.
			 **
			 **   op1=DELETE, op2=INSERT      ->      UPDATE.
			 **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
			 **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
			 */
			if op1 == int32(SQLITE_INSERT) && op2 == int32(SQLITE_INSERT) || op1 == int32(SQLITE_UPDATE) && op2 == int32(SQLITE_INSERT) || op1 == int32(SQLITE_DELETE) && op2 == int32(SQLITE_UPDATE) || op1 == int32(SQLITE_DELETE) && op2 == int32(SQLITE_DELETE) {
				pNew = pExist
			} else {
				if op1 == int32(SQLITE_INSERT) && op2 == int32(SQLITE_DELETE) {
					Xsqlite3_free(tls, pExist)
				} else {
					aExist = (*TSessionChange)(unsafe.Pointer(pExist)).FaRecord
					/* Allocate a new SessionChange object. Ensure that the aRecord[]
					 ** buffer of the new object is large enough to hold any record that
					 ** may be generated by combining the input records.  */
					nByte1 = libc.Int64FromUint32(uint32(20) + libc.Uint32FromInt32((*TSessionChange)(unsafe.Pointer(pExist)).FnRecord) + libc.Uint32FromInt32(nRec))
					pNew = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte1))
					if !(pNew != 0) {
						Xsqlite3_free(tls, pExist)
						return int32(SQLITE_NOMEM)
					}
					libc.Xmemset(tls, pNew, 0, uint32(20))
					(*TSessionChange)(unsafe.Pointer(pNew)).FbIndirect = libc.BoolUint8(bIndirect != 0 && (*TSessionChange)(unsafe.Pointer(pExist)).FbIndirect != 0)
					v2 = pNew + 1*20
					(*TSessionChange)(unsafe.Pointer(pNew)).FaRecord = v2
					**(**uintptr)(__ccgo_up(bp)) = v2
					if op1 == int32(SQLITE_INSERT) { /* INSERT + UPDATE */
						**(**uintptr)(__ccgo_up(bp + 4)) = aRec
						(*TSessionChange)(unsafe.Pointer(pNew)).Fop = uint8(SQLITE_INSERT)
						if bPatchset == 0 {
							_sessionSkipRecord(tls, bp+4, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol)
						}
						_sessionMergeRecord(tls, bp, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol, aExist, **(**uintptr)(__ccgo_up(bp + 4)))
					} else {
						if op1 == int32(SQLITE_DELETE) { /* DELETE + INSERT */
							(*TSessionChange)(unsafe.Pointer(pNew)).Fop = uint8(SQLITE_UPDATE)
							if bPatchset != 0 {
								libc.Xmemcpy(tls, **(**uintptr)(__ccgo_up(bp)), aRec, libc.Uint32FromInt32(nRec))
								**(**uintptr)(__ccgo_up(bp)) = **(**uintptr)(__ccgo_up(bp)) + uintptr(nRec)
							} else {
								if 0 == _sessionMergeUpdate(tls, bp, pTab, bPatchset, aExist, uintptr(0), aRec, uintptr(0)) {
									Xsqlite3_free(tls, pNew)
									pNew = uintptr(0)
								}
							}
						} else {
							if op2 == int32(SQLITE_UPDATE) { /* UPDATE + UPDATE */
								**(**uintptr)(__ccgo_up(bp + 8)) = aExist
								**(**uintptr)(__ccgo_up(bp + 12)) = aRec
								if bPatchset == 0 {
									_sessionSkipRecord(tls, bp+8, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol)
									_sessionSkipRecord(tls, bp+12, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol)
								}
								(*TSessionChange)(unsafe.Pointer(pNew)).Fop = uint8(SQLITE_UPDATE)
								if 0 == _sessionMergeUpdate(tls, bp, pTab, bPatchset, aRec, aExist, **(**uintptr)(__ccgo_up(bp + 8)), **(**uintptr)(__ccgo_up(bp + 12))) {
									Xsqlite3_free(tls, pNew)
									pNew = uintptr(0)
								}
							} else { /* UPDATE + DELETE */
								(*TSessionChange)(unsafe.Pointer(pNew)).Fop = uint8(SQLITE_DELETE)
								if bPatchset != 0 {
									libc.Xmemcpy(tls, **(**uintptr)(__ccgo_up(bp)), aRec, libc.Uint32FromInt32(nRec))
									**(**uintptr)(__ccgo_up(bp)) = **(**uintptr)(__ccgo_up(bp)) + uintptr(nRec)
								} else {
									_sessionMergeRecord(tls, bp, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol, aRec, aExist)
								}
							}
						}
					}
					if pNew != 0 {
						(*TSessionChange)(unsafe.Pointer(pNew)).FnRecord = int32(**(**uintptr)(__ccgo_up(bp))) - int32((*TSessionChange)(unsafe.Pointer(pNew)).FaRecord)
					}
					Xsqlite3_free(tls, pExist)
				}
			}
		}
	}
	**(**uintptr)(__ccgo_up(ppNew)) = pNew
	return rc
}

// C documentation
//
//	/*
//	** Check if a changeset entry with nCol columns and the PK array passed
//	** as the final argument to this function is compatible with SessionTable
//	** pTab. If so, return 1. Otherwise, if they are incompatible in some way,
//	** return 0.
//	*/
func _sessionChangesetCheckCompat(tls *libc.TLS, pTab uintptr, nCol int32, abPK uintptr) (r int32) {
	var bPK Tu8
	var ii, v2 int32
	_, _, _ = bPK, ii, v2
	if (*TSessionTable)(unsafe.Pointer(pTab)).FazCol != 0 && nCol < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol {
		ii = 0
		for {
			if !(ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
				break
			}
			if ii < nCol {
				v2 = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(abPK + uintptr(ii))))
			} else {
				v2 = 0
			}
			bPK = libc.Uint8FromInt32(v2)
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(ii)))) != libc.Int32FromUint8(bPK) {
				return 0
			}
			goto _1
		_1:
			;
			ii = ii + 1
		}
		return int32(1)
	}
	return libc.BoolInt32((*TSessionTable)(unsafe.Pointer(pTab)).FnCol == nCol && 0 == libc.Xmemcmp(tls, abPK, (*TSessionTable)(unsafe.Pointer(pTab)).FabPK, libc.Uint32FromInt32(nCol)))
}

func _sessionChangesetExtendRecord(tls *libc.TLS, pGrp uintptr, pTab uintptr, nCol int32, op int32, aRec uintptr, nRec int32, pOut uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var eType, iOff, ii, n int32
	var iVal Tsqlite3_int64
	var rVal float64
	var z, z1 uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _ = eType, iOff, iVal, ii, n, rVal, z, z1
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	ii = 0
	(*TSessionBuffer)(unsafe.Pointer(pOut)).FnBuf = 0
	if op == int32(SQLITE_INSERT) || op == int32(SQLITE_DELETE) && (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch == 0 {
		/* Append the missing default column values to the record. */
		_sessionAppendBlob(tls, pOut, aRec, nRec, bp)
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK && (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt == uintptr(0) {
			**(**int32)(__ccgo_up(bp)) = _sessionPrepareDfltStmt(tls, (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).Fdb, pTab, pTab+52)
			if **(**int32)(__ccgo_up(bp)) == SQLITE_OK && int32(SQLITE_ROW) != Xsqlite3_step(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt) {
				**(**int32)(__ccgo_up(bp)) = Xsqlite3_errcode(tls, (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).Fdb)
			}
		}
		ii = nCol
		for {
			if !(**(**int32)(__ccgo_up(bp)) == SQLITE_OK && ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
				break
			}
			eType = Xsqlite3_column_type(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
			_sessionAppendByte(tls, pOut, libc.Uint8FromInt32(eType), bp)
			switch eType {
			case int32(SQLITE_FLOAT):
				fallthrough
			case int32(SQLITE_INTEGER):
				if SQLITE_OK == _sessionBufferGrow(tls, pOut, int64(8), bp) {
					if eType == int32(SQLITE_INTEGER) {
						iVal = Xsqlite3_column_int64(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
						_sessionPutI64(tls, (*TSessionBuffer)(unsafe.Pointer(pOut)).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(pOut)).FnBuf), iVal)
					} else {
						rVal = Xsqlite3_column_double(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
						_sessionPutDouble(tls, (*TSessionBuffer)(unsafe.Pointer(pOut)).FaBuf+uintptr((*TSessionBuffer)(unsafe.Pointer(pOut)).FnBuf), rVal)
					}
					**(**int32)(__ccgo_up(pOut + 4)) += int32(8)
				}
			case int32(SQLITE_BLOB):
				fallthrough
			case int32(SQLITE_TEXT):
				n = Xsqlite3_column_bytes(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
				_sessionAppendVarint(tls, pOut, n, bp)
				if eType == int32(SQLITE_TEXT) {
					z = Xsqlite3_column_text(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
					_sessionAppendBlob(tls, pOut, z, n, bp)
				} else {
					z1 = Xsqlite3_column_blob(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FpDfltStmt, ii)
					_sessionAppendBlob(tls, pOut, z1, n, bp)
				}
			default:
				break
			}
			goto _1
		_1:
			;
			ii = ii + 1
		}
	} else {
		if op == int32(SQLITE_UPDATE) {
			/* Append missing "undefined" entries to the old.* record. And, if this
			 ** is an UPDATE, to the new.* record as well.  */
			iOff = 0
			if (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch == 0 {
				ii = 0
				for {
					if !(ii < nCol) {
						break
					}
					iOff = iOff + _sessionSerialLen(tls, aRec+uintptr(iOff))
					goto _2
				_2:
					;
					ii = ii + 1
				}
				_sessionAppendBlob(tls, pOut, aRec, iOff, bp)
				ii = 0
				for {
					if !(ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol-nCol) {
						break
					}
					_sessionAppendByte(tls, pOut, uint8(0x00), bp)
					goto _3
				_3:
					;
					ii = ii + 1
				}
			}
			_sessionAppendBlob(tls, pOut, aRec+uintptr(iOff), nRec-iOff, bp)
			ii = 0
			for {
				if !(ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol-nCol) {
					break
				}
				_sessionAppendByte(tls, pOut, uint8(0x00), bp)
				goto _4
			_4:
				;
				ii = ii + 1
			}
		} else {
			_sessionAppendBlob(tls, pOut, aRec, nRec, bp)
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Locate or create a SessionTable object that may be used to add the
//	** change currently pointed to by iterator pIter to changegroup pGrp.
//	** If successful, set output variable (*ppTab) to point to the table
//	** object and return SQLITE_OK. Otherwise, if some error occurs, return
//	** an SQLite error code and leave (*ppTab) set to NULL.
//	*/
func _sessionChangesetFindTable(tls *libc.TLS, pGrp uintptr, zTab uintptr, pIter uintptr, ppTab uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nTab, rc int32
	var pTab, ppNew uintptr
	var _ /* abPK at bp+0 */ uintptr
	var _ /* nCol at bp+4 */ int32
	_, _, _, _ = nTab, pTab, ppNew, rc
	rc = SQLITE_OK
	pTab = uintptr(0)
	nTab = libc.Int32FromUint32(libc.Xstrlen(tls, zTab))
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	**(**int32)(__ccgo_up(bp + 4)) = 0
	**(**uintptr)(__ccgo_up(ppTab)) = uintptr(0)
	/* Search the list for an existing table */
	pTab = (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FpList
	for {
		if !(pTab != 0) {
			break
		}
		if 0 == Xsqlite3_strnicmp(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, zTab, nTab+int32(1)) {
			break
		}
		goto _1
	_1:
		;
		pTab = (*TSessionTable)(unsafe.Pointer(pTab)).FpNext
	}
	if pIter != 0 {
		Xsqlite3changeset_pk(tls, pIter, bp, bp+4)
	} else {
		if !(pTab != 0) && !((*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).Fdb != 0) {
			return SQLITE_OK
		}
	}
	/* If one was not found above, create a new table now */
	if !(pTab != 0) {
		pTab = Xsqlite3_malloc64(tls, uint64(uint32(56)+libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4)))+libc.Uint32FromInt32(nTab)+uint32(1)))
		if !(pTab != 0) {
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, pTab, 0, uint32(56))
		(*TSessionTable)(unsafe.Pointer(pTab)).FnCol = **(**int32)(__ccgo_up(bp + 4))
		(*TSessionTable)(unsafe.Pointer(pTab)).FabPK = pTab + 1*56
		if **(**int32)(__ccgo_up(bp + 4)) > 0 {
			libc.Xmemcpy(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FabPK, **(**uintptr)(__ccgo_up(bp)), libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4))))
		}
		(*TSessionTable)(unsafe.Pointer(pTab)).FzName = (*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(**(**int32)(__ccgo_up(bp + 4)))
		libc.Xmemcpy(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, zTab, libc.Uint32FromInt32(nTab+int32(1)))
		if (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).Fdb != 0 {
			(*TSessionTable)(unsafe.Pointer(pTab)).FnCol = 0
			rc = _sessionInitTable(tls, uintptr(0), pTab, (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).Fdb, (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FzDb)
			if rc != 0 || (*TSessionTable)(unsafe.Pointer(pTab)).FnCol == 0 {
				Xsqlite3_free(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FazCol)
				Xsqlite3_free(tls, pTab)
				return rc
			}
		}
		/* The new object must be linked on to the end of the list, not
		 ** simply added to the start of it. This is to ensure that the
		 ** tables within the output of sqlite3changegroup_output() are in
		 ** the right order.  */
		ppNew = pGrp + 8
		for {
			if !(**(**uintptr)(__ccgo_up(ppNew)) != 0) {
				break
			}
			goto _2
		_2:
			;
			ppNew = **(**uintptr)(__ccgo_up(ppNew))
		}
		**(**uintptr)(__ccgo_up(ppNew)) = pTab
	}
	/* Check that the table is compatible. */
	if pIter != 0 && !(_sessionChangesetCheckCompat(tls, pTab, **(**int32)(__ccgo_up(bp + 4)), **(**uintptr)(__ccgo_up(bp))) != 0) {
		rc = int32(SQLITE_SCHEMA)
	}
	**(**uintptr)(__ccgo_up(ppTab)) = pTab
	return rc
}

func _sessionChangesetInvert(tls *libc.TLS, pInput uintptr, __ccgo_fp_xOutput uintptr, pOut uintptr, pnInverted uintptr, ppInverted uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var abPK, apVal, pVal, pVal1, v7 uintptr
	var bIndirect, eType2, iCol, nVar, v1 int32
	var eType Tu8
	var _ /* nByte at bp+32 */ int32
	var _ /* nByte at bp+36 */ int32
	var _ /* nCol at bp+16 */ int32
	var _ /* rc at bp+0 */ int32
	var _ /* sOut at bp+4 */ TSessionBuffer
	var _ /* sPK at bp+20 */ TSessionBuffer
	_, _, _, _, _, _, _, _, _, _, _ = abPK, apVal, bIndirect, eType, eType2, iCol, nVar, pVal, pVal1, v1, v7
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK                      /* Output buffer */
	**(**int32)(__ccgo_up(bp + 16)) = 0                         /* Number of cols in current table */
	abPK = uintptr(0)                                           /* PK array for current table */
	apVal = uintptr(0)                                          /* Space for values for UPDATE inversion */
	**(**TSessionBuffer)(__ccgo_up(bp + 20)) = TSessionBuffer{} /* PK array for current table */
	/* Initialize the output buffer */
	libc.Xmemset(tls, bp+4, 0, uint32(12))
	/* Zero the output variables in case an error occurs. */
	if ppInverted != 0 {
		**(**uintptr)(__ccgo_up(ppInverted)) = uintptr(0)
		**(**int32)(__ccgo_up(pnInverted)) = 0
	}
	for int32(1) != 0 {
		/* Test for EOF. */
		v1 = _sessionInputBuffer(tls, pInput, int32(2))
		**(**int32)(__ccgo_up(bp)) = v1
		if v1 != 0 {
			goto finished_invert
		}
		if (*TSessionInput)(unsafe.Pointer(pInput)).FiNext+int32(1) >= (*TSessionInput)(unsafe.Pointer(pInput)).FnData {
			if (*TSessionInput)(unsafe.Pointer(pInput)).FiNext != (*TSessionInput)(unsafe.Pointer(pInput)).FnData {
				**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(237907))
				goto finished_invert
			}
			break
		}
		eType = **(**Tu8)(__ccgo_up((*TSessionInput)(unsafe.Pointer(pInput)).FaData + uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext)))
		switch libc.Int32FromUint8(eType) {
		case int32('T'):
			(*TSessionInput)(unsafe.Pointer(pInput)).FiNext = (*TSessionInput)(unsafe.Pointer(pInput)).FiNext + 1
			v1 = _sessionChangesetBufferTblhdr(tls, pInput, bp+32)
			**(**int32)(__ccgo_up(bp)) = v1
			if v1 != 0 {
				goto finished_invert
			}
			nVar = _sessionVarintGet(tls, (*TSessionInput)(unsafe.Pointer(pInput)).FaData+uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext), bp+16)
			(**(**TSessionBuffer)(__ccgo_up(bp + 20))).FnBuf = 0
			_sessionAppendBlob(tls, bp+20, (*TSessionInput)(unsafe.Pointer(pInput)).FaData+uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext+nVar), **(**int32)(__ccgo_up(bp + 16)), bp)
			_sessionAppendByte(tls, bp+4, eType, bp)
			_sessionAppendBlob(tls, bp+4, (*TSessionInput)(unsafe.Pointer(pInput)).FaData+uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext), **(**int32)(__ccgo_up(bp + 32)), bp)
			if **(**int32)(__ccgo_up(bp)) != 0 {
				goto finished_invert
			}
			**(**int32)(__ccgo_up(pInput + 8)) += **(**int32)(__ccgo_up(bp + 32))
			Xsqlite3_free(tls, apVal)
			apVal = uintptr(0)
			abPK = (**(**TSessionBuffer)(__ccgo_up(bp + 20))).FaBuf
		case int32(SQLITE_INSERT):
			fallthrough
		case int32(SQLITE_DELETE):
			bIndirect = libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionInput)(unsafe.Pointer(pInput)).FaData + uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext+int32(1)))))
			if libc.Int32FromUint8(eType) == int32(SQLITE_DELETE) {
				v1 = int32(SQLITE_INSERT)
			} else {
				v1 = int32(SQLITE_DELETE)
			}
			eType2 = v1
			**(**int32)(__ccgo_up(pInput + 8)) += int32(2)
			**(**int32)(__ccgo_up(bp)) = _sessionChangesetBufferRecord(tls, pInput, **(**int32)(__ccgo_up(bp + 16)), bp+36)
			_sessionAppendByte(tls, bp+4, libc.Uint8FromInt32(eType2), bp)
			_sessionAppendByte(tls, bp+4, libc.Uint8FromInt32(bIndirect), bp)
			_sessionAppendBlob(tls, bp+4, (*TSessionInput)(unsafe.Pointer(pInput)).FaData+uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext), **(**int32)(__ccgo_up(bp + 36)), bp)
			**(**int32)(__ccgo_up(pInput + 8)) += **(**int32)(__ccgo_up(bp + 36))
			if **(**int32)(__ccgo_up(bp)) != 0 {
				goto finished_invert
			}
		case int32(SQLITE_UPDATE):
			if uintptr(0) == apVal {
				apVal = Xsqlite3_malloc64(tls, uint64(uint32(4)*libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 16)))*uint32(2)))
				if uintptr(0) == apVal {
					**(**int32)(__ccgo_up(bp)) = int32(SQLITE_NOMEM)
					goto finished_invert
				}
				libc.Xmemset(tls, apVal, 0, uint32(4)*libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 16)))*uint32(2))
			}
			/* Write the header for the new UPDATE change. Same as the original. */
			_sessionAppendByte(tls, bp+4, eType, bp)
			_sessionAppendByte(tls, bp+4, **(**Tu8)(__ccgo_up((*TSessionInput)(unsafe.Pointer(pInput)).FaData + uintptr((*TSessionInput)(unsafe.Pointer(pInput)).FiNext+int32(1)))), bp)
			/* Read the old.* and new.* records for the update change. */
			**(**int32)(__ccgo_up(pInput + 8)) += int32(2)
			**(**int32)(__ccgo_up(bp)) = _sessionReadRecord(tls, pInput, **(**int32)(__ccgo_up(bp + 16)), uintptr(0), apVal, uintptr(0))
			if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
				**(**int32)(__ccgo_up(bp)) = _sessionReadRecord(tls, pInput, **(**int32)(__ccgo_up(bp + 16)), uintptr(0), apVal+uintptr(**(**int32)(__ccgo_up(bp + 16)))*4, uintptr(0))
			}
			/* Write the new old.* record. Consists of the PK columns from the
			 ** original old.* record, and the other values from the original
			 ** new.* record. */
			iCol = 0
			for {
				if !(iCol < **(**int32)(__ccgo_up(bp + 16))) {
					break
				}
				if **(**Tu8)(__ccgo_up(abPK + uintptr(iCol))) != 0 {
					v1 = 0
				} else {
					v1 = **(**int32)(__ccgo_up(bp + 16))
				}
				pVal = **(**uintptr)(__ccgo_up(apVal + uintptr(iCol+v1)*4))
				_sessionAppendValue(tls, bp+4, pVal, bp)
				goto _4
			_4:
				;
				iCol = iCol + 1
			}
			/* Write the new new.* record. Consists of a copy of all values
			 ** from the original old.* record, except for the PK columns, which
			 ** are set to "undefined". */
			iCol = 0
			for {
				if !(iCol < **(**int32)(__ccgo_up(bp + 16))) {
					break
				}
				if **(**Tu8)(__ccgo_up(abPK + uintptr(iCol))) != 0 {
					v7 = uintptr(0)
				} else {
					v7 = **(**uintptr)(__ccgo_up(apVal + uintptr(iCol)*4))
				}
				pVal1 = v7
				_sessionAppendValue(tls, bp+4, pVal1, bp)
				goto _6
			_6:
				;
				iCol = iCol + 1
			}
			iCol = 0
			for {
				if !(iCol < **(**int32)(__ccgo_up(bp + 16))*int32(2)) {
					break
				}
				_sqlite3ValueFree(tls, **(**uintptr)(__ccgo_up(apVal + uintptr(iCol)*4)))
				goto _8
			_8:
				;
				iCol = iCol + 1
			}
			libc.Xmemset(tls, apVal, 0, uint32(4)*libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 16)))*uint32(2))
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				goto finished_invert
			}
		default:
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(238010))
			goto finished_invert
		}
		if __ccgo_fp_xOutput != 0 && (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf >= _sessions_strm_chunk_size {
			**(**int32)(__ccgo_up(bp)) = (*(*func(*libc.TLS, uintptr, uintptr, int32) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xOutput})))(tls, pOut, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf)
			(**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf = 0
			if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
				goto finished_invert
			}
		}
	}
	if pnInverted != 0 && ppInverted != 0 {
		**(**int32)(__ccgo_up(pnInverted)) = (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf
		**(**uintptr)(__ccgo_up(ppInverted)) = (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf
		(**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf = uintptr(0)
	} else {
		if (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf > 0 && __ccgo_fp_xOutput != uintptr(0) {
			**(**int32)(__ccgo_up(bp)) = (*(*func(*libc.TLS, uintptr, uintptr, int32) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xOutput})))(tls, pOut, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FnBuf)
		}
	}
	goto finished_invert
finished_invert:
	;
	Xsqlite3_free(tls, (**(**TSessionBuffer)(__ccgo_up(bp + 4))).FaBuf)
	Xsqlite3_free(tls, apVal)
	Xsqlite3_free(tls, (**(**TSessionBuffer)(__ccgo_up(bp + 20))).FaBuf)
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Advance the changeset iterator to the next change. The differences between
//	** this function and sessionChangesetNext() are that
//	**
//	**   * If pbEmpty is not NULL and the change is a no-op UPDATE (an UPDATE
//	**     that modifies no columns), this function sets (*pbEmpty) to 1.
//	**
//	**   * If the iterator is configured to skip no-op UPDATEs,
//	**     sessionChangesetNext() does that. This function does not.
//	*/
func _sessionChangesetNextOne(tls *libc.TLS, p uintptr, paRec uintptr, pnRec uintptr, pbNew uintptr, pbEmpty uintptr) (r int32) {
	var abPK, apNew, apOld, v10, v3, v6 uintptr
	var i, nVal, v2 int32
	var op Tu8
	_, _, _, _, _, _, _, _, _, _ = abPK, apNew, apOld, i, nVal, op, v10, v2, v3, v6
	/* If the iterator is in the error-state, return immediately. */
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc != SQLITE_OK {
		return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
	}
	/* Free the current contents of p->apValue[], if any. */
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue != 0 {
		i = 0
		for {
			if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol*int32(2)) {
				break
			}
			_sqlite3ValueFree(tls, **(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i)*4)))
			goto _1
		_1:
			;
			i = i + 1
		}
		libc.Xmemset(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue, 0, uint32(4)*libc.Uint32FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*uint32(2))
	}
	/* Make sure the buffer contains at least 2 bytes of input data, or all
	 ** remaining data if there are less than 2 bytes available. This is
	 ** sufficient either for the 'T' or 'P' byte that begins a new table,
	 ** or for the "op" and "bIndirect" single bytes otherwise. */
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = _sessionInputBuffer(tls, p, int32(2))
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc != SQLITE_OK {
		return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
	}
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiCurrent = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext
	_sessionDiscardData(tls, p)
	/* If the iterator is already at the end of the changeset, return DONE. */
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext >= (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FnData {
		return int32(SQLITE_DONE)
	}
	v3 = p + 8
	v2 = *(*int32)(unsafe.Pointer(v3))
	*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
	op = **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData + uintptr(v2)))
	for libc.Int32FromUint8(op) == int32('T') || libc.Int32FromUint8(op) == int32('P') {
		if pbNew != 0 {
			**(**int32)(__ccgo_up(pbNew)) = int32(1)
		}
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset = libc.BoolInt32(libc.Int32FromUint8(op) == int32('P'))
		if _sessionChangesetReadTblhdr(tls, p) != 0 {
			return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
		}
		v2 = _sessionInputBuffer(tls, p, int32(2))
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = v2
		if v2 != 0 {
			return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
		}
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiCurrent = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext >= (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FnData {
			return int32(SQLITE_DONE)
		}
		v3 = p + 8
		v2 = *(*int32)(unsafe.Pointer(v3))
		*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
		op = **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData + uintptr(v2)))
	}
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FzTab == uintptr(0) || (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset != 0 && (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbInvert != 0 {
		/* The first record in the changeset is not a table header. Must be a
		 ** corrupt changeset. */
		v2 = _sqlite3CorruptError(tls, int32(237587))
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = v2
		return v2
	}
	if libc.Int32FromUint8(op) != int32(SQLITE_UPDATE) && libc.Int32FromUint8(op) != int32(SQLITE_DELETE) && libc.Int32FromUint8(op) != int32(SQLITE_INSERT) || (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext >= (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FnData {
		v2 = _sqlite3CorruptError(tls, int32(237593))
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = v2
		return v2
	}
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop = libc.Int32FromUint8(op)
	v3 = p + 8
	v2 = *(*int32)(unsafe.Pointer(v3))
	*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbIndirect = libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData + uintptr(v2))))
	if paRec != 0 { /* Number of values to buffer */
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset == 0 && libc.Int32FromUint8(op) == int32(SQLITE_UPDATE) {
			nVal = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol * int32(2)
		} else {
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset != 0 && libc.Int32FromUint8(op) == int32(SQLITE_DELETE) {
				nVal = 0
				i = 0
				for {
					if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol) {
						break
					}
					if **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK + uintptr(i))) != 0 {
						nVal = nVal + 1
					}
					goto _11
				_11:
					;
					i = i + 1
				}
			} else {
				nVal = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol
			}
		}
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = _sessionChangesetBufferRecord(tls, p, nVal, pnRec)
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc != SQLITE_OK {
			return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
		}
		**(**uintptr)(__ccgo_up(paRec)) = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext)
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext += **(**int32)(__ccgo_up(pnRec))
	} else {
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbInvert != 0 {
			v3 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*4
		} else {
			v3 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue
		}
		apOld = v3
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbInvert != 0 {
			v6 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue
		} else {
			v6 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*4
		}
		apNew = v6
		/* If this is an UPDATE or DELETE, read the old.* record. */
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop != int32(SQLITE_INSERT) && ((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset == 0 || (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop == int32(SQLITE_DELETE)) {
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset != 0 {
				v10 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK
			} else {
				v10 = uintptr(0)
			}
			abPK = v10
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = _sessionReadRecord(tls, p, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol, abPK, apOld, uintptr(0))
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc != SQLITE_OK {
				return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
			}
		}
		/* If this is an INSERT or UPDATE, read the new.* record. */
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop != int32(SQLITE_DELETE) {
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = _sessionReadRecord(tls, p, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol, uintptr(0), apNew, pbEmpty)
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc != SQLITE_OK {
				return (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc
			}
		}
		if ((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset != 0 || (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbInvert != 0) && (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop == int32(SQLITE_UPDATE) {
			/* If this is an UPDATE that is part of a patchset, then all PK and
			 ** modified fields are present in the new.* record. The old.* record
			 ** is currently completely empty. This block shifts the PK fields from
			 ** new.* to old.*, to accommodate the code that reads these arrays.  */
			i = 0
			for {
				if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol) {
					break
				}
				if **(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK + uintptr(i))) != 0 {
					**(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i)*4)) = **(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i+(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*4))
					if **(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i)*4)) == uintptr(0) {
						v2 = _sqlite3CorruptError(tls, int32(237639))
						(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = v2
						return v2
					}
					**(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i+(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*4)) = uintptr(0)
				}
				goto _15
			_15:
				;
				i = i + 1
			}
		} else {
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbInvert != 0 {
				if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop == int32(SQLITE_INSERT) {
					(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop = int32(SQLITE_DELETE)
				} else {
					if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop == int32(SQLITE_DELETE) {
						(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop = int32(SQLITE_INSERT)
					}
				}
			}
		}
		/* If this is an UPDATE that is part of a changeset, then check that
		 ** there are no fields in the old.* record that are not (a) PK fields,
		 ** or (b) also present in the new.* record.
		 **
		 ** Such records are technically corrupt, but the rebaser was at one
		 ** point generating them. Under most circumstances this is benign, but
		 ** can cause spurious SQLITE_RANGE errors when applying the changeset. */
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FbPatchset == 0 && (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fop == int32(SQLITE_UPDATE) {
			i = 0
			for {
				if !(i < (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol) {
					break
				}
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK + uintptr(i)))) == 0 && **(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i+(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*4)) == uintptr(0) {
					_sqlite3ValueFree(tls, **(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i)*4)))
					**(**uintptr)(__ccgo_up((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr(i)*4)) = uintptr(0)
				}
				goto _17
			_17:
				;
				i = i + 1
			}
		}
	}
	return int32(SQLITE_ROW)
}

// C documentation
//
//	/*
//	** The input pointer currently points to the second byte of a table-header.
//	** Specifically, to the following:
//	**
//	**   + number of columns in table (varint)
//	**   + array of PK flags (1 byte per column),
//	**   + table name (nul terminated).
//	**
//	** This function decodes the table-header and populates the p->nCol,
//	** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
//	** also allocated or resized according to the new value of p->nCol. The
//	** input pointer is left pointing to the byte following the table header.
//	**
//	** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
//	** is returned and the final values of the various fields enumerated above
//	** are undefined.
//	*/
func _sessionChangesetReadTblhdr(tls *libc.TLS, p uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iPK Tsize_t
	var nByte, nVarint, v2 int32
	var v1 uintptr
	var _ /* nCopy at bp+4 */ int32
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _ = iPK, nByte, nVarint, v1, v2
	**(**int32)(__ccgo_up(bp)) = _sessionChangesetBufferTblhdr(tls, p, bp+4)
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		nVarint = _sessionVarintGet(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData+uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext), p+80)
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol > 0 {
			**(**int32)(__ccgo_up(bp + 4)) = **(**int32)(__ccgo_up(bp + 4)) - nVarint
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext += nVarint
			nByte = libc.Int32FromUint32(libc.Uint32FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)*uint32(4)*uint32(2) + libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4))))
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Ftblhdr.FnBuf = 0
			_sessionBufferGrow(tls, p+44, int64(nByte), bp)
		} else {
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(237501))
		}
	}
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		iPK = uint32(4) * libc.Uint32FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol) * uint32(2)
		libc.Xmemset(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Ftblhdr.FaBuf, 0, iPK)
		libc.Xmemcpy(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Ftblhdr.FaBuf+uintptr(iPK), (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FaData+uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext), libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 4))))
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Fin.FiNext += **(**int32)(__ccgo_up(bp + 4))
	}
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Ftblhdr.FaBuf
	if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue == uintptr(0) {
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK = uintptr(0)
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FzTab = uintptr(0)
	} else {
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FapValue + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol*int32(2))*4
		if (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK != 0 {
			v1 = (*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FabPK + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FnCol)
		} else {
			v1 = uintptr(0)
		}
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).FzTab = v1
	}
	v2 = **(**int32)(__ccgo_up(bp))
	(*Tsqlite3_changeset_iter)(unsafe.Pointer(p)).Frc = v2
	return v2
}

// C documentation
//
//	/*
//	** Invoke the conflict handler for the change that the changeset iterator
//	** currently points to.
//	**
//	** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
//	** If argument pbReplace is NULL, then the type of conflict handler invoked
//	** depends solely on eType, as follows:
//	**
//	**    eType value                 Value passed to xConflict
//	**    -------------------------------------------------
//	**    CHANGESET_DATA              CHANGESET_NOTFOUND
//	**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
//	**
//	** Or, if pbReplace is not NULL, then an attempt is made to find an existing
//	** record with the same primary key as the record about to be deleted, updated
//	** or inserted. If such a record can be found, it is available to the conflict
//	** handler as the "conflicting" record. In this case the type of conflict
//	** handler invoked is as follows:
//	**
//	**    eType value         PK Record found?   Value passed to xConflict
//	**    ----------------------------------------------------------------
//	**    CHANGESET_DATA      Yes                CHANGESET_DATA
//	**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
//	**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
//	**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
//	**
//	** If pbReplace is not NULL, and a record with a matching PK is found, and
//	** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
//	** is set to non-zero before returning SQLITE_OK.
//	**
//	** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
//	** returned. Or, if the conflict handler returns an invalid value,
//	** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
//	** this function returns SQLITE_OK.
//	*/
func _sessionConflictHandler(tls *libc.TLS, eType int32, p uintptr, pIter uintptr, __ccgo_fp_xConflict uintptr, pCtx uintptr, pbReplace uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aBlob uintptr
	var nBlob, res int32
	var _ /* nCol at bp+4 */ int32
	var _ /* op at bp+8 */ int32
	var _ /* rc at bp+0 */ int32
	var _ /* zDummy at bp+12 */ uintptr
	_, _, _ = aBlob, nBlob, res
	res = SQLITE_CHANGESET_OMIT
	Xsqlite3changeset_op(tls, pIter, bp+12, bp+4, bp+8, uintptr(0))
	/* Bind the new.* PRIMARY KEY values to the SELECT statement. */
	if pbReplace != 0 {
		**(**int32)(__ccgo_up(bp)) = _sessionSeekToRow(tls, pIter, p)
	} else {
		**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	}
	if **(**int32)(__ccgo_up(bp)) == int32(SQLITE_ROW) {
		/* There exists another row with the new.* primary key. */
		if 0 == libc.Int32FromUint8((*TSessionApplyCtx)(unsafe.Pointer(p)).FbIgnoreNoop) || 0 == Xsqlite3_column_int(tls, (*TSessionApplyCtx)(unsafe.Pointer(p)).FpSelect, Xsqlite3_column_count(tls, (*TSessionApplyCtx)(unsafe.Pointer(p)).FpSelect)-int32(1)) {
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FpConflict = (*TSessionApplyCtx)(unsafe.Pointer(p)).FpSelect
			res = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xConflict})))(tls, pCtx, eType, pIter)
			(*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FpConflict = uintptr(0)
		}
		**(**int32)(__ccgo_up(bp)) = Xsqlite3_reset(tls, (*TSessionApplyCtx)(unsafe.Pointer(p)).FpSelect)
	} else {
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			if (*TSessionApplyCtx)(unsafe.Pointer(p)).FbDeferConstraints != 0 && eType == int32(SQLITE_CHANGESET_CONFLICT) {
				/* Instead of invoking the conflict handler, append the change blob
				 ** to the SessionApplyCtx.constraints buffer. */
				aBlob = (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fin.FaData + uintptr((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fin.FiCurrent)
				nBlob = (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fin.FiNext - (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fin.FiCurrent
				_sessionAppendBlob(tls, p+48, aBlob, nBlob, bp)
				return **(**int32)(__ccgo_up(bp))
			} else {
				if libc.Int32FromUint8((*TSessionApplyCtx)(unsafe.Pointer(p)).FbIgnoreNoop) == 0 || **(**int32)(__ccgo_up(bp + 8)) != int32(SQLITE_DELETE) || eType == int32(SQLITE_CHANGESET_CONFLICT) {
					/* No other row with the new.* primary key. */
					res = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xConflict})))(tls, pCtx, eType+int32(1), pIter)
					if res == int32(SQLITE_CHANGESET_REPLACE) {
						**(**int32)(__ccgo_up(bp)) = int32(SQLITE_MISUSE)
					}
				}
			}
		}
	}
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		switch res {
		case int32(SQLITE_CHANGESET_REPLACE):
			**(**int32)(__ccgo_up(pbReplace)) = int32(1)
		case SQLITE_CHANGESET_OMIT:
		case int32(SQLITE_CHANGESET_ABORT):
			**(**int32)(__ccgo_up(bp)) = int32(SQLITE_ABORT)
		default:
			**(**int32)(__ccgo_up(bp)) = int32(SQLITE_MISUSE)
			break
		}
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			**(**int32)(__ccgo_up(bp)) = _sessionRebaseAdd(tls, p, res, pIter)
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** If the SessionInput object passed as the only argument is a streaming
//	** object and the buffer is full, discard some data to free up space.
//	*/
func _sessionDiscardData(tls *libc.TLS, pIn uintptr) {
	var nMove int32
	_ = nMove
	if (*TSessionInput)(unsafe.Pointer(pIn)).FxInput != 0 && (*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent >= _sessions_strm_chunk_size {
		nMove = (*TSessionInput)(unsafe.Pointer(pIn)).Fbuf.FnBuf - (*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent
		if nMove > 0 {
			libc.Xmemmove(tls, (*TSessionInput)(unsafe.Pointer(pIn)).Fbuf.FaBuf, (*TSessionInput)(unsafe.Pointer(pIn)).Fbuf.FaBuf+uintptr((*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent), libc.Uint32FromInt32(nMove))
		}
		(*TSessionInput)(unsafe.Pointer(pIn)).Fbuf.FnBuf -= (*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent
		**(**int32)(__ccgo_up(pIn + 8)) -= (*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent
		(*TSessionInput)(unsafe.Pointer(pIn)).FiCurrent = 0
		(*TSessionInput)(unsafe.Pointer(pIn)).FnData = (*TSessionInput)(unsafe.Pointer(pIn)).Fbuf.FnBuf
	}
}

// C documentation
//
//	/*
//	** If required, grow the hash table used to store changes on table pTab
//	** (part of the session pSession). If a fatal OOM error occurs, set the
//	** session object to failed and return SQLITE_ERROR. Otherwise, return
//	** SQLITE_OK.
//	**
//	** It is possible that a non-fatal OOM error occurs in this function. In
//	** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
//	** Growing the hash table in this case is a performance optimization only,
//	** it is not required for correct operation.
//	*/
func _sessionGrowHash(tls *libc.TLS, pSession uintptr, bPatchset int32, pTab uintptr) (r int32) {
	var apNew, p, pNext uintptr
	var bPkOnly, i, iHash, v1 int32
	var nNew Tsqlite3_int64
	_, _, _, _, _, _, _, _ = apNew, bPkOnly, i, iHash, nNew, p, pNext, v1
	if (*TSessionTable)(unsafe.Pointer(pTab)).FnChange == 0 || (*TSessionTable)(unsafe.Pointer(pTab)).FnEntry >= (*TSessionTable)(unsafe.Pointer(pTab)).FnChange/int32(2) {
		if (*TSessionTable)(unsafe.Pointer(pTab)).FnChange != 0 {
			v1 = (*TSessionTable)(unsafe.Pointer(pTab)).FnChange
		} else {
			v1 = int32(128)
		}
		nNew = int64(2) * int64(v1)
		apNew = _sessionMalloc64(tls, pSession, int64(4)*nNew)
		if apNew == uintptr(0) {
			if (*TSessionTable)(unsafe.Pointer(pTab)).FnChange == 0 {
				return int32(SQLITE_ERROR)
			}
			return SQLITE_OK
		}
		libc.Xmemset(tls, apNew, 0, libc.Uint32FromInt64(int64(4)*nNew))
		i = 0
		for {
			if !(i < (*TSessionTable)(unsafe.Pointer(pTab)).FnChange) {
				break
			}
			p = **(**uintptr)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(i)*4))
			for {
				if !(p != 0) {
					break
				}
				bPkOnly = libc.BoolInt32(libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(p)).Fop) == int32(SQLITE_DELETE) && bPatchset != 0)
				iHash = libc.Int32FromUint32(_sessionChangeHash(tls, pTab, bPkOnly, (*TSessionChange)(unsafe.Pointer(p)).FaRecord, int32(nNew)))
				pNext = (*TSessionChange)(unsafe.Pointer(p)).FpNext
				(*TSessionChange)(unsafe.Pointer(p)).FpNext = **(**uintptr)(__ccgo_up(apNew + uintptr(iHash)*4))
				**(**uintptr)(__ccgo_up(apNew + uintptr(iHash)*4)) = p
				goto _3
			_3:
				;
				p = pNext
			}
			goto _2
		_2:
			;
			i = i + 1
		}
		_sessionFree(tls, pSession, (*TSessionTable)(unsafe.Pointer(pTab)).FapChange)
		(*TSessionTable)(unsafe.Pointer(pTab)).FnChange = int32(nNew)
		(*TSessionTable)(unsafe.Pointer(pTab)).FapChange = apNew
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Allocate and return a pointer to a buffer nByte bytes in size. If
//	** pSession is not NULL, increase the sqlite3_session.nMalloc variable
//	** by the number of bytes allocated.
//	*/
func _sessionMalloc64(tls *libc.TLS, pSession uintptr, nByte Ti64) (r uintptr) {
	var pRet, v1 uintptr
	_, _ = pRet, v1
	pRet = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
	if pSession != 0 {
		v1 = pSession + 40
		*(*Ti64)(unsafe.Pointer(v1)) = Ti64(uint64(*(*Ti64)(unsafe.Pointer(v1))) + Xsqlite3_msize(tls, pRet))
	}
	return pRet
}

// C documentation
//
//	/*
//	** Arguments aLeft and aRight both point to buffers containing change
//	** records with nCol columns. This function "merges" the two records into
//	** a single records which is written to the buffer at *paOut. *paOut is
//	** then set to point to one byte after the last byte written before
//	** returning.
//	**
//	** The merging of records is done as follows: For each column, if the
//	** aRight record contains a value for the column, copy the value from
//	** their. Otherwise, if aLeft contains a value, copy it. If neither
//	** record contains a value for a given column, then neither does the
//	** output record.
//	*/
func _sessionMergeRecord(tls *libc.TLS, paOut uintptr, nCol int32, aLeft uintptr, aRight uintptr) {
	var a1, a2, aOut uintptr
	var iCol, n1, n2 int32
	_, _, _, _, _, _ = a1, a2, aOut, iCol, n1, n2
	a1 = aLeft                             /* Cursor used to iterate through aLeft */
	a2 = aRight                            /* Cursor used to iterate through aRight */
	aOut = **(**uintptr)(__ccgo_up(paOut)) /* Used to iterate from 0 to nCol */
	iCol = 0
	for {
		if !(iCol < nCol) {
			break
		}
		n1 = _sessionSerialLen(tls, a1)
		n2 = _sessionSerialLen(tls, a2)
		if **(**Tu8)(__ccgo_up(a2)) != 0 {
			libc.Xmemcpy(tls, aOut, a2, libc.Uint32FromInt32(n2))
			aOut = aOut + uintptr(n2)
		} else {
			libc.Xmemcpy(tls, aOut, a1, libc.Uint32FromInt32(n1))
			aOut = aOut + uintptr(n1)
		}
		a1 = a1 + uintptr(n1)
		a2 = a2 + uintptr(n2)
		goto _1
	_1:
		;
		iCol = iCol + 1
	}
	**(**uintptr)(__ccgo_up(paOut)) = aOut
}

// C documentation
//
//	/*
//	** This function is used by changeset_concat() to merge two UPDATE changes
//	** on the same row.
//	*/
func _sessionMergeUpdate(tls *libc.TLS, paOut uintptr, pTab uintptr, bPatchset int32, aOldRecord1 uintptr, aOldRecord2 uintptr, aNewRecord1 uintptr, aNewRecord2 uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var aNew, aNew1, aOld, aOld1, aOut, v2 uintptr
	var bRequired, i int32
	var _ /* aNew1 at bp+8 */ uintptr
	var _ /* aNew2 at bp+12 */ uintptr
	var _ /* aOld1 at bp+0 */ uintptr
	var _ /* aOld2 at bp+4 */ uintptr
	var _ /* nNew at bp+20 */ int32
	var _ /* nNew at bp+28 */ int32
	var _ /* nOld at bp+16 */ int32
	var _ /* nOld at bp+24 */ int32
	_, _, _, _, _, _, _, _ = aNew, aNew1, aOld, aOld1, aOut, bRequired, i, v2
	**(**uintptr)(__ccgo_up(bp)) = aOldRecord1
	**(**uintptr)(__ccgo_up(bp + 4)) = aOldRecord2
	**(**uintptr)(__ccgo_up(bp + 8)) = aNewRecord1
	**(**uintptr)(__ccgo_up(bp + 12)) = aNewRecord2
	aOut = **(**uintptr)(__ccgo_up(paOut))
	if bPatchset == 0 {
		bRequired = 0
		/* Write the old.* vector first. */
		i = 0
		for {
			if !(i < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
				break
			}
			aOld = _sessionMergeValue(tls, bp, bp+4, bp+16)
			aNew = _sessionMergeValue(tls, bp+8, bp+12, bp+20)
			if **(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i))) != 0 || **(**int32)(__ccgo_up(bp + 16)) != **(**int32)(__ccgo_up(bp + 20)) || libc.Xmemcmp(tls, aOld, aNew, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 20)))) != 0 {
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i)))) == 0 {
					bRequired = int32(1)
				}
				libc.Xmemcpy(tls, aOut, aOld, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 16))))
				aOut = aOut + uintptr(**(**int32)(__ccgo_up(bp + 16)))
			} else {
				v2 = aOut
				aOut = aOut + 1
				**(**Tu8)(__ccgo_up(v2)) = uint8('\000')
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		if !(bRequired != 0) {
			return 0
		}
	}
	/* Write the new.* vector */
	**(**uintptr)(__ccgo_up(bp)) = aOldRecord1
	**(**uintptr)(__ccgo_up(bp + 4)) = aOldRecord2
	**(**uintptr)(__ccgo_up(bp + 8)) = aNewRecord1
	**(**uintptr)(__ccgo_up(bp + 12)) = aNewRecord2
	i = 0
	for {
		if !(i < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
			break
		}
		aOld1 = _sessionMergeValue(tls, bp, bp+4, bp+24)
		aNew1 = _sessionMergeValue(tls, bp+8, bp+12, bp+28)
		if bPatchset == 0 && (**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i))) != 0 || **(**int32)(__ccgo_up(bp + 24)) == **(**int32)(__ccgo_up(bp + 28)) && 0 == libc.Xmemcmp(tls, aOld1, aNew1, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 28))))) {
			v2 = aOut
			aOut = aOut + 1
			**(**Tu8)(__ccgo_up(v2)) = uint8('\000')
		} else {
			libc.Xmemcpy(tls, aOut, aNew1, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 28))))
			aOut = aOut + uintptr(**(**int32)(__ccgo_up(bp + 28)))
		}
		goto _3
	_3:
		;
		i = i + 1
	}
	**(**uintptr)(__ccgo_up(paOut)) = aOut
	return int32(1)
}

// C documentation
//
//	/*
//	** Add a single change to the changegroup pGrp.
//	*/
func _sessionOneChangeToHash(tls *libc.TLS, pGrp uintptr, pTab uintptr, op int32, bIndirect int32, nCol int32, aRec uintptr, nRec int32, bRebase int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var bPkOnly1, bPkOnly2, iHash, rc int32
	var pBuf, pExist, pp uintptr
	var _ /* pChange at bp+0 */ uintptr
	_, _, _, _, _, _, _ = bPkOnly1, bPkOnly2, iHash, pBuf, pExist, pp, rc
	rc = SQLITE_OK
	iHash = 0
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	pExist = uintptr(0)
	pp = uintptr(0)
	if nCol < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol {
		pBuf = pGrp + 12
		rc = _sessionChangesetExtendRecord(tls, pGrp, pTab, nCol, op, aRec, nRec, pBuf)
		aRec = (*TSessionBuffer)(unsafe.Pointer(pBuf)).FaBuf
		nRec = (*TSessionBuffer)(unsafe.Pointer(pBuf)).FnBuf
	}
	if rc == SQLITE_OK && _sessionGrowHash(tls, uintptr(0), (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch, pTab) != 0 {
		rc = int32(SQLITE_NOMEM)
	}
	if rc == SQLITE_OK {
		/* Search for existing entry. If found, remove it from the hash table.
		 ** Code below may link it back in.  */
		iHash = libc.Int32FromUint32(_sessionChangeHash(tls, pTab, libc.BoolInt32((*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch != 0 && op == int32(SQLITE_DELETE)), aRec, (*TSessionTable)(unsafe.Pointer(pTab)).FnChange))
		pp = (*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(iHash)*4
		for {
			if !(**(**uintptr)(__ccgo_up(pp)) != 0) {
				break
			}
			bPkOnly1 = 0
			bPkOnly2 = 0
			if (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch != 0 {
				bPkOnly1 = libc.BoolInt32(libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(**(**uintptr)(__ccgo_up(pp)))).Fop) == int32(SQLITE_DELETE))
				bPkOnly2 = libc.BoolInt32(op == int32(SQLITE_DELETE))
			}
			if _sessionChangeEqual(tls, pTab, bPkOnly1, (*TSessionChange)(unsafe.Pointer(**(**uintptr)(__ccgo_up(pp)))).FaRecord, bPkOnly2, aRec) != 0 {
				pExist = **(**uintptr)(__ccgo_up(pp))
				**(**uintptr)(__ccgo_up(pp)) = (*TSessionChange)(unsafe.Pointer(**(**uintptr)(__ccgo_up(pp)))).FpNext
				(*TSessionTable)(unsafe.Pointer(pTab)).FnEntry = (*TSessionTable)(unsafe.Pointer(pTab)).FnEntry - 1
				break
			}
			goto _1
		_1:
			;
			pp = **(**uintptr)(__ccgo_up(pp)) + 16
		}
	}
	if rc == SQLITE_OK {
		rc = _sessionChangeMerge(tls, pTab, bRebase, (*Tsqlite3_changegroup)(unsafe.Pointer(pGrp)).FbPatch, pExist, op, bIndirect, aRec, nRec, bp)
	}
	if rc == SQLITE_OK && **(**uintptr)(__ccgo_up(bp)) != 0 {
		(*TSessionChange)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FpNext = **(**uintptr)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(iHash)*4))
		**(**uintptr)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(iHash)*4)) = **(**uintptr)(__ccgo_up(bp))
		(*TSessionTable)(unsafe.Pointer(pTab)).FnEntry = (*TSessionTable)(unsafe.Pointer(pTab)).FnEntry + 1
	}
	return rc
}

// C documentation
//
//	/*
//	** This function is only called from within a pre-update-hook callback.
//	** It determines if the current pre-update-hook change affects the same row
//	** as the change stored in argument pChange. If so, it returns true. Otherwise
//	** if the pre-update-hook does not affect the same row as pChange, it returns
//	** false.
//	*/
func _sessionPreupdateEqual(tls *libc.TLS, pSession uintptr, iRowid Ti64, pTab uintptr, pChange uintptr, op int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var a, z, v2 uintptr
	var eType, iCol, iIdx, rc int32
	var _ /* iVal at bp+8 */ Ti64
	var _ /* n at bp+24 */ int32
	var _ /* pVal at bp+0 */ uintptr
	var _ /* rVal at bp+16 */ float64
	_, _, _, _, _, _, _ = a, eType, iCol, iIdx, rc, z, v2   /* Used to iterate through columns */
	a = (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord /* Cursor used to scan change record */
	if (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid != 0 {
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(a))) != int32(SQLITE_INTEGER) {
			return 0
		}
		return libc.BoolInt32(_sessionGetI64(tls, a+1) == iRowid)
	}
	iCol = 0
	for {
		if !(iCol < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
			break
		}
		if !(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(iCol))) != 0) {
			a = a + uintptr(_sessionSerialLen(tls, a))
		} else {
			v2 = a
			a = a + 1                                             /* Error code from preupdate_new/old */
			eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v2))) /* Type of value from change record */
			iIdx = **(**int32)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FaiIdx + uintptr(iCol)*4))
			/* The following calls to preupdate_new() and preupdate_old() can not
			 ** fail. This is because they cache their return values, and by the
			 ** time control flows to here they have already been called once from
			 ** within sessionPreupdateHash(). The first two asserts below verify
			 ** this (that the method has already been called). */
			if op == int32(SQLITE_INSERT) {
				/* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
				rc = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxNew})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, iIdx, bp)
			} else {
				/* assert( db->pPreUpdate->pUnpacked ); */
				rc = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxOld})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, iIdx, bp)
			}
			_ = rc /* Suppress warning about unused variable */
			if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(bp))) != eType {
				return 0
			}
			/* A SessionChange object never has a NULL value in a PK column */
			if eType == int32(SQLITE_INTEGER) || eType == int32(SQLITE_FLOAT) {
				**(**Ti64)(__ccgo_up(bp + 8)) = _sessionGetI64(tls, a)
				a = a + uintptr(8)
				if eType == int32(SQLITE_INTEGER) {
					if Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(bp))) != **(**Ti64)(__ccgo_up(bp + 8)) {
						return 0
					}
				} else {
					libc.Xmemcpy(tls, bp+16, bp+8, uint32(8))
					if Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(bp))) != **(**float64)(__ccgo_up(bp + 16)) {
						return 0
					}
				}
			} else {
				a = a + uintptr(_sessionVarintGet(tls, a, bp+24))
				if Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(bp))) != **(**int32)(__ccgo_up(bp + 24)) {
					return 0
				}
				if eType == int32(SQLITE_TEXT) {
					z = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(bp)))
				} else {
					z = Xsqlite3_value_blob(tls, **(**uintptr)(__ccgo_up(bp)))
				}
				if **(**int32)(__ccgo_up(bp + 24)) > 0 && libc.Xmemcmp(tls, a, z, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 24)))) != 0 {
					return 0
				}
				a = a + uintptr(**(**int32)(__ccgo_up(bp + 24)))
			}
		}
		goto _1
	_1:
		;
		iCol = iCol + 1
	}
	return int32(1)
}

// C documentation
//
//	/*
//	** This function may only be called from within a pre-update callback.
//	** It calculates a hash based on the primary key values of the old.* or
//	** new.* row currently available and, assuming no error occurs, writes it to
//	** *piHash before returning. If the primary key contains one or more NULL
//	** values, *pbNullPK is set to true before returning.
//	**
//	** If an error occurs, an SQLite error code is returned and the final values
//	** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
//	** and the output variables are set as described above.
//	*/
func _sessionPreupdateHash(tls *libc.TLS, pSession uintptr, iRowid Ti64, pTab uintptr, bNew int32, piHash uintptr, pbNullPK uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var eType, i, iIdx, n, rc int32
	var h uint32
	var z uintptr
	var _ /* iVal at bp+8 */ Ti64
	var _ /* pVal at bp+0 */ uintptr
	var _ /* rVal at bp+16 */ float64
	_, _, _, _, _, _, _ = eType, h, i, iIdx, n, rc, z
	h = uint32(0) /* Used to iterate through columns */
	if (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid != 0 {
		h = _sessionHashAppendI64(tls, h, iRowid)
	} else {
		i = 0
		for {
			if !(i < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
				break
			}
			if **(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(i))) != 0 {
				iIdx = **(**int32)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FaiIdx + uintptr(i)*4))
				if bNew != 0 {
					rc = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxNew})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, iIdx, bp)
				} else {
					rc = (*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxOld})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, iIdx, bp)
				}
				if rc != SQLITE_OK {
					return rc
				}
				eType = Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(bp)))
				h = _sessionHashAppendType(tls, h, eType)
				if eType == int32(SQLITE_INTEGER) || eType == int32(SQLITE_FLOAT) {
					if eType == int32(SQLITE_INTEGER) {
						**(**Ti64)(__ccgo_up(bp + 8)) = Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(bp)))
					} else {
						**(**float64)(__ccgo_up(bp + 16)) = Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(bp)))
						libc.Xmemcpy(tls, bp+8, bp+16, uint32(8))
					}
					h = _sessionHashAppendI64(tls, h, **(**Ti64)(__ccgo_up(bp + 8)))
				} else {
					if eType == int32(SQLITE_TEXT) || eType == int32(SQLITE_BLOB) {
						if eType == int32(SQLITE_TEXT) {
							z = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(bp)))
						} else {
							z = Xsqlite3_value_blob(tls, **(**uintptr)(__ccgo_up(bp)))
						}
						n = Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(bp)))
						if !(z != 0) && (eType != int32(SQLITE_BLOB) || n > 0) {
							return int32(SQLITE_NOMEM)
						}
						h = _sessionHashAppendBlob(tls, h, n, z)
					} else {
						**(**int32)(__ccgo_up(pbNullPK)) = int32(1)
					}
				}
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	**(**int32)(__ccgo_up(piHash)) = libc.Int32FromUint32(h % libc.Uint32FromInt32((*TSessionTable)(unsafe.Pointer(pTab)).FnChange))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Write a double value to the buffer aBuf[].
//	*/
func _sessionPutDouble(tls *libc.TLS, aBuf uintptr, _r float64) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	*(*float64)(unsafe.Pointer(bp)) = _r
	var _ /* i at bp+8 */ Tu64
	libc.Xmemcpy(tls, bp+8, bp, uint32(8))
	_sessionPutI64(tls, aBuf, libc.Int64FromUint64(**(**Tu64)(__ccgo_up(bp + 8))))
}

// C documentation
//
//	/*
//	** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
//	** for details.
//	**
//	** When this function is called, *paChange points to the start of the record
//	** to deserialize. Assuming no error occurs, *paChange is set to point to
//	** one byte after the end of the same record before this function returns.
//	** If the argument abPK is NULL, then the record contains nCol values. Or,
//	** if abPK is other than NULL, then the record contains only the PK fields
//	** (in other words, it is a patchset DELETE record).
//	**
//	** If successful, each element of the apOut[] array (allocated by the caller)
//	** is set to point to an sqlite3_value object containing the value read
//	** from the corresponding position in the record. If that value is not
//	** included in the record (i.e. because the record is part of an UPDATE change
//	** and the field was not modified), the corresponding element of apOut[] is
//	** set to NULL.
//	**
//	** It is the responsibility of the caller to free all sqlite_value structures
//	** using sqlite3_free().
//	**
//	** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
//	** The apOut[] array may have been partially populated in this case.
//	*/
func _sessionReadRecord(tls *libc.TLS, pIn uintptr, nCol int32, abPK uintptr, apOut uintptr, pbEmpty uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var aVal, v3 uintptr
	var eType, i, nRem, rc, v2 int32
	var enc Tu8
	var _ /* d at bp+16 */ float64
	var _ /* nByte at bp+0 */ int32
	var _ /* v at bp+8 */ Tsqlite3_int64
	_, _, _, _, _, _, _, _ = aVal, eType, enc, i, nRem, rc, v2, v3 /* Used to iterate through columns */
	rc = SQLITE_OK
	if pbEmpty != 0 {
		**(**int32)(__ccgo_up(pbEmpty)) = int32(1)
	}
	i = 0
	for {
		if !(i < nCol && rc == SQLITE_OK) {
			break
		}
		eType = 0 /* Type of value (SQLITE_NULL, TEXT etc.) */
		if abPK != 0 && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(abPK + uintptr(i)))) == 0 {
			goto _1
		}
		rc = _sessionInputBuffer(tls, pIn, int32(9))
		if rc == SQLITE_OK {
			if (*TSessionInput)(unsafe.Pointer(pIn)).FiNext >= (*TSessionInput)(unsafe.Pointer(pIn)).FnData {
				rc = _sqlite3CorruptError(tls, int32(237320))
			} else {
				v3 = pIn + 8
				v2 = *(*int32)(unsafe.Pointer(v3))
				*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
				eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionInput)(unsafe.Pointer(pIn)).FaData + uintptr(v2))))
				if eType != 0 {
					if pbEmpty != 0 {
						**(**int32)(__ccgo_up(pbEmpty)) = 0
					}
					**(**uintptr)(__ccgo_up(apOut + uintptr(i)*4)) = _sqlite3ValueNew(tls, uintptr(0))
					if !(**(**uintptr)(__ccgo_up(apOut + uintptr(i)*4)) != 0) {
						rc = int32(SQLITE_NOMEM)
					}
				}
			}
		}
		if rc == SQLITE_OK {
			aVal = (*TSessionInput)(unsafe.Pointer(pIn)).FaData + uintptr((*TSessionInput)(unsafe.Pointer(pIn)).FiNext)
			if eType == int32(SQLITE_TEXT) || eType == int32(SQLITE_BLOB) {
				nRem = (*TSessionInput)(unsafe.Pointer(pIn)).FnData - (*TSessionInput)(unsafe.Pointer(pIn)).FiNext
				**(**int32)(__ccgo_up(pIn + 8)) += _sessionVarintGetSafe(tls, aVal, nRem, bp)
				rc = _sessionInputBuffer(tls, pIn, **(**int32)(__ccgo_up(bp)))
				if rc == SQLITE_OK {
					if **(**int32)(__ccgo_up(bp)) < 0 || **(**int32)(__ccgo_up(bp)) > (*TSessionInput)(unsafe.Pointer(pIn)).FnData-(*TSessionInput)(unsafe.Pointer(pIn)).FiNext {
						rc = _sqlite3CorruptError(tls, int32(237341))
					} else {
						if eType == int32(SQLITE_TEXT) {
							v2 = int32(SQLITE_UTF8)
						} else {
							v2 = 0
						}
						enc = libc.Uint8FromInt32(v2)
						rc = _sessionValueSetStr(tls, **(**uintptr)(__ccgo_up(apOut + uintptr(i)*4)), (*TSessionInput)(unsafe.Pointer(pIn)).FaData+uintptr((*TSessionInput)(unsafe.Pointer(pIn)).FiNext), **(**int32)(__ccgo_up(bp)), enc)
						**(**int32)(__ccgo_up(pIn + 8)) += **(**int32)(__ccgo_up(bp))
					}
				}
			}
			if eType == int32(SQLITE_INTEGER) || eType == int32(SQLITE_FLOAT) {
				if (*TSessionInput)(unsafe.Pointer(pIn)).FnData-(*TSessionInput)(unsafe.Pointer(pIn)).FiNext < int32(8) {
					rc = _sqlite3CorruptError(tls, int32(237351))
				} else {
					**(**Tsqlite3_int64)(__ccgo_up(bp + 8)) = _sessionGetI64(tls, aVal)
					if eType == int32(SQLITE_INTEGER) {
						_sqlite3VdbeMemSetInt64(tls, **(**uintptr)(__ccgo_up(apOut + uintptr(i)*4)), **(**Tsqlite3_int64)(__ccgo_up(bp + 8)))
					} else {
						libc.Xmemcpy(tls, bp+16, bp+8, uint32(8))
						_sqlite3VdbeMemSetDouble(tls, **(**uintptr)(__ccgo_up(apOut + uintptr(i)*4)), **(**float64)(__ccgo_up(bp + 16)))
					}
					**(**int32)(__ccgo_up(pIn + 8)) += int32(8)
				}
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return rc
}

// C documentation
//
//	/*
//	** pIter is configured to iterate through a changeset. This function rebases
//	** that changeset according to the current configuration of the rebaser
//	** object passed as the first argument. If no error occurs and argument xOutput
//	** is not NULL, then the changeset is returned to the caller by invoking
//	** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
//	** then (*ppOut) is set to point to a buffer containing the rebased changeset
//	** before this function returns. In this case (*pnOut) is set to the size of
//	** the buffer in bytes.  It is the responsibility of the caller to eventually
//	** free the (*ppOut) buffer using sqlite3_free().
//	**
//	** If an error occurs, an SQLite error code is returned. If ppOut and
//	** pnOut are not NULL, then the two output parameters are set to 0 before
//	** returning.
//	*/
func _sessionRebase(tls *libc.TLS, p uintptr, pIter uintptr, __ccgo_fp_xOutput uintptr, pOut uintptr, pnOut uintptr, ppOut uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var bDone, iHash, v2 int32
	var pChange, pTab, zTab uintptr
	var _ /* aRec at bp+4 */ uintptr
	var _ /* bNew at bp+12 */ int32
	var _ /* nRec at bp+8 */ int32
	var _ /* pCsr at bp+28 */ uintptr
	var _ /* rc at bp+0 */ int32
	var _ /* sOut at bp+16 */ TSessionBuffer
	_, _, _, _, _, _ = bDone, iHash, pChange, pTab, zTab, v2
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
	**(**int32)(__ccgo_up(bp + 8)) = 0
	**(**int32)(__ccgo_up(bp + 12)) = 0
	pTab = uintptr(0)
	**(**TSessionBuffer)(__ccgo_up(bp + 16)) = TSessionBuffer{}
	for int32(SQLITE_ROW) == _sessionChangesetNext(tls, pIter, bp+4, bp+8, bp+12) {
		pChange = uintptr(0)
		bDone = 0
		if **(**int32)(__ccgo_up(bp + 12)) != 0 {
			zTab = (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FzTab
			pTab = (*Tsqlite3_rebaser)(unsafe.Pointer(p)).Fgrp.FpList
			for {
				if !(pTab != 0) {
					break
				}
				if 0 == Xsqlite3_stricmp(tls, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, zTab) {
					break
				}
				goto _1
			_1:
				;
				pTab = (*TSessionTable)(unsafe.Pointer(pTab)).FpNext
			}
			**(**int32)(__ccgo_up(bp + 12)) = 0
			/* A patchset may not be rebased */
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbPatchset != 0 {
				**(**int32)(__ccgo_up(bp)) = int32(SQLITE_ERROR)
			}
			/* Append a table header to the output for this new table */
			if (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbPatchset != 0 {
				v2 = int32('P')
			} else {
				v2 = int32('T')
			}
			_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32(v2), bp)
			_sessionAppendVarint(tls, bp+16, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol, bp)
			_sessionAppendBlob(tls, bp+16, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FabPK, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol, bp)
			_sessionAppendBlob(tls, bp+16, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FzTab, libc.Int32FromUint32(libc.Xstrlen(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FzTab))+int32(1), bp)
		}
		if pTab != 0 && **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			iHash = libc.Int32FromUint32(_sessionChangeHash(tls, pTab, 0, **(**uintptr)(__ccgo_up(bp + 4)), (*TSessionTable)(unsafe.Pointer(pTab)).FnChange))
			pChange = **(**uintptr)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(iHash)*4))
			for {
				if !(pChange != 0) {
					break
				}
				if _sessionChangeEqual(tls, pTab, 0, **(**uintptr)(__ccgo_up(bp + 4)), 0, (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord) != 0 {
					break
				}
				goto _3
			_3:
				;
				pChange = (*TSessionChange)(unsafe.Pointer(pChange)).FpNext
			}
		}
		if pChange != 0 {
			switch (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fop {
			case int32(SQLITE_INSERT):
				if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pChange)).Fop) == int32(SQLITE_INSERT) {
					bDone = int32(1)
					if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pChange)).FbIndirect) == 0 {
						_sessionAppendByte(tls, bp+16, uint8(SQLITE_UPDATE), bp)
						_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbIndirect), bp)
						_sessionAppendBlob(tls, bp+16, (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord, (*TSessionChange)(unsafe.Pointer(pChange)).FnRecord, bp)
						_sessionAppendBlob(tls, bp+16, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp + 8)), bp)
					}
				}
			case int32(SQLITE_UPDATE):
				bDone = int32(1)
				if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pChange)).Fop) == int32(SQLITE_DELETE) {
					if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pChange)).FbIndirect) == 0 {
						**(**uintptr)(__ccgo_up(bp + 28)) = **(**uintptr)(__ccgo_up(bp + 4))
						_sessionSkipRecord(tls, bp+28, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol)
						_sessionAppendByte(tls, bp+16, uint8(SQLITE_INSERT), bp)
						_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbIndirect), bp)
						_sessionAppendRecordMerge(tls, bp+16, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol, **(**uintptr)(__ccgo_up(bp + 28)), **(**int32)(__ccgo_up(bp + 8))-(int32(**(**uintptr)(__ccgo_up(bp + 28)))-int32(**(**uintptr)(__ccgo_up(bp + 4)))), (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord, (*TSessionChange)(unsafe.Pointer(pChange)).FnRecord, bp)
					}
				} else {
					_sessionAppendPartialUpdate(tls, bp+16, pIter, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp + 8)), (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord, (*TSessionChange)(unsafe.Pointer(pChange)).FnRecord, bp)
				}
			default:
				bDone = int32(1)
				if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pChange)).Fop) == int32(SQLITE_INSERT) {
					_sessionAppendByte(tls, bp+16, uint8(SQLITE_DELETE), bp)
					_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbIndirect), bp)
					_sessionAppendRecordMerge(tls, bp+16, (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FnCol, (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord, (*TSessionChange)(unsafe.Pointer(pChange)).FnRecord, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp + 8)), bp)
				}
				break
			}
		}
		if bDone == 0 {
			_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fop), bp)
			_sessionAppendByte(tls, bp+16, libc.Uint8FromInt32((*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FbIndirect), bp)
			_sessionAppendBlob(tls, bp+16, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp + 8)), bp)
		}
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK && __ccgo_fp_xOutput != 0 && (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf > _sessions_strm_chunk_size {
			**(**int32)(__ccgo_up(bp)) = (*(*func(*libc.TLS, uintptr, uintptr, int32) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xOutput})))(tls, pOut, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf)
			(**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf = 0
		}
		if **(**int32)(__ccgo_up(bp)) != 0 {
			break
		}
	}
	if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
		Xsqlite3_free(tls, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf)
		libc.Xmemset(tls, bp+16, 0, uint32(12))
	}
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		if __ccgo_fp_xOutput != 0 {
			if (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf > 0 {
				**(**int32)(__ccgo_up(bp)) = (*(*func(*libc.TLS, uintptr, uintptr, int32) int32)(unsafe.Pointer(&struct{ uintptr }{__ccgo_fp_xOutput})))(tls, pOut, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf)
			}
		} else {
			if ppOut != 0 {
				**(**uintptr)(__ccgo_up(ppOut)) = (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf
				**(**int32)(__ccgo_up(pnOut)) = (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FnBuf
				(**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf = uintptr(0)
			}
		}
	}
	Xsqlite3_free(tls, (**(**TSessionBuffer)(__ccgo_up(bp + 16))).FaBuf)
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** This function is called from within sqlite3changeset_apply_v2() when
//	** a conflict is encountered and resolved using conflict resolution
//	** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
//	** It adds a conflict resolution record to the buffer in
//	** SessionApplyCtx.rebase, which will eventually be returned to the caller
//	** of apply_v2() as the "rebase" buffer.
//	**
//	** Return SQLITE_OK if successful, or an SQLite error code otherwise.
//	*/
func _sessionRebaseAdd(tls *libc.TLS, p uintptr, eType int32, pIter uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var eOp, i, v1 int32
	var zTab uintptr
	var _ /* pVal at bp+4 */ uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _, _ = eOp, i, zTab, v1
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK
	if (*TSessionApplyCtx)(unsafe.Pointer(p)).FbRebase != 0 {
		eOp = (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).Fop
		if libc.Int32FromUint8((*TSessionApplyCtx)(unsafe.Pointer(p)).FbRebaseStarted) == 0 {
			/* Append a table-header to the rebase buffer */
			zTab = (*Tsqlite3_changeset_iter)(unsafe.Pointer(pIter)).FzTab
			_sessionAppendByte(tls, p+60, uint8('T'), bp)
			_sessionAppendVarint(tls, p+60, (*TSessionApplyCtx)(unsafe.Pointer(p)).FnCol, bp)
			_sessionAppendBlob(tls, p+60, (*TSessionApplyCtx)(unsafe.Pointer(p)).FabPK, (*TSessionApplyCtx)(unsafe.Pointer(p)).FnCol, bp)
			_sessionAppendBlob(tls, p+60, zTab, libc.Int32FromUint32(libc.Xstrlen(tls, zTab))+int32(1), bp)
			(*TSessionApplyCtx)(unsafe.Pointer(p)).FbRebaseStarted = uint8(1)
		}
		if eOp == int32(SQLITE_DELETE) {
			v1 = int32(SQLITE_DELETE)
		} else {
			v1 = int32(SQLITE_INSERT)
		}
		_sessionAppendByte(tls, p+60, libc.Uint8FromInt32(v1), bp)
		_sessionAppendByte(tls, p+60, libc.BoolUint8(eType == libc.Int32FromInt32(SQLITE_CHANGESET_REPLACE)), bp)
		i = 0
		for {
			if !(i < (*TSessionApplyCtx)(unsafe.Pointer(p)).FnCol) {
				break
			}
			**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
			if eOp == int32(SQLITE_DELETE) || eOp == int32(SQLITE_UPDATE) && **(**Tu8)(__ccgo_up((*TSessionApplyCtx)(unsafe.Pointer(p)).FabPK + uintptr(i))) != 0 {
				Xsqlite3changeset_old(tls, pIter, i, bp+4)
			} else {
				Xsqlite3changeset_new(tls, pIter, i, bp+4)
			}
			_sessionAppendValue(tls, p+60, **(**uintptr)(__ccgo_up(bp + 4)), bp)
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Re-initialize table object pTab.
//	*/
func _sessionReinitTable(tls *libc.TLS, pSession uintptr, pTab uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var a, v1 uintptr
	var ii, nOldCol int32
	var _ /* abPK at bp+20 */ uintptr
	var _ /* aiIdx at bp+16 */ uintptr
	var _ /* azCol at bp+8 */ uintptr
	var _ /* azDflt at bp+12 */ uintptr
	var _ /* bRowid at bp+24 */ int32
	var _ /* nCol at bp+0 */ int32
	var _ /* nTotalCol at bp+4 */ int32
	_, _, _, _ = a, ii, nOldCol, v1
	**(**int32)(__ccgo_up(bp)) = 0
	**(**int32)(__ccgo_up(bp + 4)) = 0
	**(**uintptr)(__ccgo_up(bp + 8)) = uintptr(0)
	**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
	**(**uintptr)(__ccgo_up(bp + 16)) = uintptr(0)
	**(**uintptr)(__ccgo_up(bp + 20)) = uintptr(0)
	**(**int32)(__ccgo_up(bp + 24)) = 0
	if (*Tsqlite3_session)(unsafe.Pointer(pSession)).FbImplicitPK != 0 {
		v1 = bp + 24
	} else {
		v1 = uintptr(0)
	}
	(*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc = _sessionTableInfo(tls, pSession, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fdb, (*Tsqlite3_session)(unsafe.Pointer(pSession)).FzDb, (*TSessionTable)(unsafe.Pointer(pTab)).FzName, bp, bp+4, uintptr(0), bp+8, bp+12, bp+16, bp+20, v1)
	if (*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc == SQLITE_OK {
		if (*TSessionTable)(unsafe.Pointer(pTab)).FnCol > **(**int32)(__ccgo_up(bp)) || (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid != **(**int32)(__ccgo_up(bp + 24)) {
			(*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc = int32(SQLITE_SCHEMA)
		} else {
			nOldCol = (*TSessionTable)(unsafe.Pointer(pTab)).FnCol
			ii = 0
			for {
				if !(ii < **(**int32)(__ccgo_up(bp))) {
					break
				}
				if ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol {
					if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(ii)))) != libc.Int32FromUint8(**(**Tu8)(__ccgo_up(**(**uintptr)(__ccgo_up(bp + 20)) + uintptr(ii)))) {
						(*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc = int32(SQLITE_SCHEMA)
					}
				} else {
					if **(**Tu8)(__ccgo_up(**(**uintptr)(__ccgo_up(bp + 20)) + uintptr(ii))) != 0 {
						(*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc = int32(SQLITE_SCHEMA)
					}
				}
				goto _2
			_2:
				;
				ii = ii + 1
			}
			if (*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc == SQLITE_OK {
				a = (*TSessionTable)(unsafe.Pointer(pTab)).FazCol
				(*TSessionTable)(unsafe.Pointer(pTab)).FazCol = **(**uintptr)(__ccgo_up(bp + 8))
				(*TSessionTable)(unsafe.Pointer(pTab)).FnCol = **(**int32)(__ccgo_up(bp))
				(*TSessionTable)(unsafe.Pointer(pTab)).FnTotalCol = **(**int32)(__ccgo_up(bp + 4))
				(*TSessionTable)(unsafe.Pointer(pTab)).FazDflt = **(**uintptr)(__ccgo_up(bp + 12))
				(*TSessionTable)(unsafe.Pointer(pTab)).FabPK = **(**uintptr)(__ccgo_up(bp + 20))
				(*TSessionTable)(unsafe.Pointer(pTab)).FaiIdx = **(**uintptr)(__ccgo_up(bp + 16))
				**(**uintptr)(__ccgo_up(bp + 8)) = a
			}
			if (*Tsqlite3_session)(unsafe.Pointer(pSession)).FbEnableSize != 0 {
				**(**Ti64)(__ccgo_up(pSession + 48)) += int64(**(**int32)(__ccgo_up(bp)) - nOldCol)
				**(**Ti64)(__ccgo_up(pSession + 48)) += int64(_sessionVarintLen(tls, **(**int32)(__ccgo_up(bp))))
				**(**Ti64)(__ccgo_up(pSession + 48)) -= int64(_sessionVarintLen(tls, nOldCol))
			}
		}
	}
	Xsqlite3_free(tls, **(**uintptr)(__ccgo_up(bp + 8)))
	return (*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc
}

// C documentation
//
//	/*
//	** Create an iterator to iterate through the retry buffer pRetry.
//	*/
func _sessionRetryIterInit(tls *libc.TLS, pRetry uintptr, bPatchset int32, zTab uintptr, pApply uintptr, ppIter uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var nByte Tsize_t
	var _ /* pRet at bp+0 */ uintptr
	var _ /* rc at bp+4 */ int32
	_ = nByte
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	**(**int32)(__ccgo_up(bp + 4)) = SQLITE_OK
	**(**int32)(__ccgo_up(bp + 4)) = _sessionChangesetStart(tls, bp, uintptr(0), uintptr(0), (*TSessionBuffer)(unsafe.Pointer(pRetry)).FnBuf, (*TSessionBuffer)(unsafe.Pointer(pRetry)).FaBuf, (*TSessionApplyCtx)(unsafe.Pointer(pApply)).FbInvertConstraints, int32(1))
	if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK {
		nByte = libc.Uint32FromInt32(int32(2)*(*TSessionApplyCtx)(unsafe.Pointer(pApply)).FnCol) * uint32(4)
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FbPatchset = bPatchset
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FzTab = zTab
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnCol = (*TSessionApplyCtx)(unsafe.Pointer(pApply)).FnCol
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FabPK = (*TSessionApplyCtx)(unsafe.Pointer(pApply)).FabPK
		_sessionBufferGrow(tls, **(**uintptr)(__ccgo_up(bp))+44, libc.Int64FromUint32(nByte), bp+4)
		(*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FapValue = (*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Ftblhdr.FaBuf
		if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK {
			libc.Xmemset(tls, (*Tsqlite3_changeset_iter)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FapValue, 0, nByte)
		} else {
			Xsqlite3changeset_finalize(tls, **(**uintptr)(__ccgo_up(bp)))
			**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
		}
	}
	**(**uintptr)(__ccgo_up(ppIter)) = **(**uintptr)(__ccgo_up(bp))
	return **(**int32)(__ccgo_up(bp + 4))
}

// C documentation
//
//	/*
//	** SQL statement pSelect is as generated by the sessionSelectRow() function.
//	** This function binds the primary key values from the change that changeset
//	** iterator pIter points to to the SELECT and attempts to seek to the table
//	** entry. If a row is found, the SELECT statement left pointing at the row
//	** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
//	** has occured, the statement is reset and SQLITE_OK is returned. If an
//	** error occurs, the statement is reset and an SQLite error code is returned.
//	**
//	** If this function returns SQLITE_ROW, the caller must eventually reset()
//	** statement pSelect. If any other value is returned, the statement does
//	** not require a reset().
//	**
//	** If the iterator currently points to an INSERT record, bind values from the
//	** new.* record to the SELECT statement. Or, if it points to a DELETE or
//	** UPDATE, bind values from the old.* record.
//	*/
func _sessionSeekToRow(tls *libc.TLS, pIter uintptr, p uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var ii, rc int32
	var pSelect, v1 uintptr
	var _ /* nCol at bp+0 */ int32
	var _ /* op at bp+4 */ int32
	var _ /* pVal at bp+12 */ uintptr
	var _ /* zDummy at bp+8 */ uintptr
	_, _, _, _ = ii, pSelect, rc, v1
	pSelect = (*TSessionApplyCtx)(unsafe.Pointer(p)).FpSelect /* Unused */
	Xsqlite3_clear_bindings(tls, pSelect)
	Xsqlite3changeset_op(tls, pIter, bp+8, bp, bp+4, uintptr(0))
	if **(**int32)(__ccgo_up(bp + 4)) == int32(SQLITE_INSERT) {
		v1 = __ccgo_fp(Xsqlite3changeset_new)
	} else {
		v1 = __ccgo_fp(Xsqlite3changeset_old)
	}
	rc = _sessionBindRow(tls, pIter, v1, **(**int32)(__ccgo_up(bp)), (*TSessionApplyCtx)(unsafe.Pointer(p)).FabPK, pSelect)
	if **(**int32)(__ccgo_up(bp + 4)) != int32(SQLITE_DELETE) && (*TSessionApplyCtx)(unsafe.Pointer(p)).FbIgnoreNoop != 0 {
		ii = 0
		for {
			if !(rc == SQLITE_OK && ii < **(**int32)(__ccgo_up(bp))) {
				break
			}
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TSessionApplyCtx)(unsafe.Pointer(p)).FabPK + uintptr(ii)))) == 0 {
				**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
				Xsqlite3changeset_new(tls, pIter, ii, bp+12)
				Xsqlite3_bind_int(tls, pSelect, ii+int32(1)+**(**int32)(__ccgo_up(bp)), libc.BoolInt32(**(**uintptr)(__ccgo_up(bp + 12)) == uintptr(0)))
				if **(**uintptr)(__ccgo_up(bp + 12)) != 0 {
					rc = _sessionBindValue(tls, pSelect, ii+int32(1), **(**uintptr)(__ccgo_up(bp + 12)))
				}
			}
			goto _2
		_2:
			;
			ii = ii + 1
		}
	}
	if rc == SQLITE_OK {
		rc = Xsqlite3_step(tls, pSelect)
		if rc != int32(SQLITE_ROW) {
			rc = Xsqlite3_reset(tls, pSelect)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Bind the PRIMARY KEY values from the change passed in argument pChange
//	** to the SELECT statement passed as the first argument. The SELECT statement
//	** is as prepared by function sessionSelectStmt().
//	**
//	** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
//	** error code (e.g. SQLITE_NOMEM) otherwise.
//	*/
func _sessionSelectBind(tls *libc.TLS, pSelect uintptr, nCol int32, abPK uintptr, pChange uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var a, v2 uintptr
	var eType, i, rc int32
	var iVal Ti64
	var _ /* iVal at bp+8 */ Ti64
	var _ /* n at bp+16 */ int32
	var _ /* n at bp+20 */ int32
	var _ /* rVal at bp+0 */ float64
	_, _, _, _, _, _ = a, eType, i, iVal, rc, v2
	rc = SQLITE_OK
	a = (*TSessionChange)(unsafe.Pointer(pChange)).FaRecord
	i = 0
	for {
		if !(i < nCol && rc == SQLITE_OK) {
			break
		}
		v2 = a
		a = a + 1
		eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v2)))
		switch eType {
		case 0:
			fallthrough
		case int32(SQLITE_NULL):
		case int32(SQLITE_INTEGER):
			if **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				iVal = _sessionGetI64(tls, a)
				rc = Xsqlite3_bind_int64(tls, pSelect, i+int32(1), iVal)
			}
			a = a + uintptr(8)
		case int32(SQLITE_FLOAT):
			if **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				**(**Ti64)(__ccgo_up(bp + 8)) = _sessionGetI64(tls, a)
				libc.Xmemcpy(tls, bp, bp+8, uint32(8))
				rc = Xsqlite3_bind_double(tls, pSelect, i+int32(1), **(**float64)(__ccgo_up(bp)))
			}
			a = a + uintptr(8)
		case int32(SQLITE_TEXT):
			a = a + uintptr(_sessionVarintGet(tls, a, bp+16))
			if **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				rc = Xsqlite3_bind_text(tls, pSelect, i+int32(1), a, **(**int32)(__ccgo_up(bp + 16)), uintptr(-libc.Int32FromInt32(1)))
			}
			a = a + uintptr(**(**int32)(__ccgo_up(bp + 16)))
		default:
			a = a + uintptr(_sessionVarintGet(tls, a, bp+20))
			if **(**Tu8)(__ccgo_up(abPK + uintptr(i))) != 0 {
				rc = Xsqlite3_bind_blob(tls, pSelect, i+int32(1), a, **(**int32)(__ccgo_up(bp + 20)), uintptr(-libc.Int32FromInt32(1)))
			}
			a = a + uintptr(**(**int32)(__ccgo_up(bp + 20)))
			break
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return rc
}

// C documentation
//
//	/*
//	** This function is used to serialize the contents of value pValue (see
//	** comment titled "RECORD FORMAT" above).
//	**
//	** If it is non-NULL, the serialized form of the value is written to
//	** buffer aBuf. *pnWrite is set to the number of bytes written before
//	** returning. Or, if aBuf is NULL, the only thing this function does is
//	** set *pnWrite.
//	**
//	** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
//	** within a call to sqlite3_value_text() (may fail if the db is utf-16))
//	** SQLITE_NOMEM is returned.
//	*/
func _sessionSerializeValue(tls *libc.TLS, aBuf uintptr, pValue uintptr, pnWrite uintptr) (r1 int32) {
	var eType, n, nByte, nVarint int32
	var i Tu64
	var r float64
	var z uintptr
	_, _, _, _, _, _, _ = eType, i, n, nByte, nVarint, r, z /* Size of serialized value in bytes */
	if pValue != 0 {                                        /* Value type (SQLITE_NULL, TEXT etc.) */
		eType = Xsqlite3_value_type(tls, pValue)
		if aBuf != 0 {
			**(**Tu8)(__ccgo_up(aBuf)) = libc.Uint8FromInt32(eType)
		}
		switch eType {
		case int32(SQLITE_NULL):
			nByte = int32(1)
		case int32(SQLITE_INTEGER):
			fallthrough
		case int32(SQLITE_FLOAT):
			if aBuf != 0 {
				/* TODO: SQLite does something special to deal with mixed-endian
				 ** floating point values (e.g. ARM7). This code probably should
				 ** too.  */
				if eType == int32(SQLITE_INTEGER) {
					i = libc.Uint64FromInt64(Xsqlite3_value_int64(tls, pValue))
					_sessionPutI64(tls, aBuf+1, libc.Int64FromUint64(i))
				} else {
					r = Xsqlite3_value_double(tls, pValue)
					_sessionPutDouble(tls, aBuf+1, r)
				}
			}
			nByte = int32(9)
		default:
			if eType == int32(SQLITE_TEXT) {
				z = Xsqlite3_value_text(tls, pValue)
			} else {
				z = Xsqlite3_value_blob(tls, pValue)
			}
			n = Xsqlite3_value_bytes(tls, pValue)
			if z == uintptr(0) && (eType != int32(SQLITE_BLOB) || n > 0) {
				return int32(SQLITE_NOMEM)
			}
			nVarint = _sessionVarintLen(tls, n)
			if aBuf != 0 {
				_sessionVarintPut(tls, aBuf+1, n)
				if n > 0 {
					libc.Xmemcpy(tls, aBuf+uintptr(nVarint+int32(1)), z, libc.Uint32FromInt32(n))
				}
			}
			nByte = int32(1) + nVarint + n
			break
		}
	} else {
		nByte = int32(1)
		if aBuf != 0 {
			**(**Tu8)(__ccgo_up(aBuf)) = uint8('\000')
		}
	}
	if pnWrite != 0 {
		**(**Tsqlite3_int64)(__ccgo_up(pnWrite)) += int64(nByte)
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Table pTab has one or more existing change-records with old.* records
//	** with fewer than pTab->nCol columns. This function updates all such
//	** change-records with the default values for the missing columns.
//	*/
func _sessionUpdateChanges(tls *libc.TLS, pSession uintptr, pTab uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var ii int32
	var pp uintptr
	var _ /* pStmt at bp+0 */ uintptr
	var _ /* rc at bp+4 */ int32
	_, _ = ii, pp
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	**(**int32)(__ccgo_up(bp + 4)) = (*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc
	**(**int32)(__ccgo_up(bp + 4)) = _sessionPrepareDfltStmt(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fdb, pTab, bp)
	if **(**int32)(__ccgo_up(bp + 4)) == SQLITE_OK && int32(SQLITE_ROW) == Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp))) {
		ii = 0
		pp = uintptr(0)
		ii = 0
		for {
			if !(ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnChange) {
				break
			}
			pp = (*TSessionTable)(unsafe.Pointer(pTab)).FapChange + uintptr(ii)*4
			for {
				if !(**(**uintptr)(__ccgo_up(pp)) != 0) {
					break
				}
				if libc.Int32FromUint16((*TSessionChange)(unsafe.Pointer(**(**uintptr)(__ccgo_up(pp)))).FnRecordField) != (*TSessionTable)(unsafe.Pointer(pTab)).FnCol {
					_sessionUpdateOneChange(tls, pSession, bp+4, pp, (*TSessionTable)(unsafe.Pointer(pTab)).FnCol, **(**uintptr)(__ccgo_up(bp)))
				}
				goto _2
			_2:
				;
				pp = **(**uintptr)(__ccgo_up(pp)) + 16
			}
			goto _1
		_1:
			;
			ii = ii + 1
		}
	}
	_sessionFinalizeStmt(tls, **(**uintptr)(__ccgo_up(bp)), bp+4)
	(*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc = **(**int32)(__ccgo_up(bp + 4))
	return (*Tsqlite3_session)(unsafe.Pointer(pSession)).Frc
}

func _sessionUpdateMaxSize(tls *libc.TLS, op int32, pSession uintptr, pTab uintptr, pC uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var bChanged, eType, iIdx, ii, ii1, nIncr, nOld int32
	var pCsr, v3 uintptr
	var _ /* dVal at bp+24 */ float64
	var _ /* iVal at bp+16 */ Tsqlite3_int64
	var _ /* nByte at bp+32 */ int32
	var _ /* nNew at bp+0 */ Ti64
	var _ /* p at bp+12 */ uintptr
	var _ /* p at bp+8 */ uintptr
	_, _, _, _, _, _, _, _, _ = bChanged, eType, iIdx, ii, ii1, nIncr, nOld, pCsr, v3
	**(**Ti64)(__ccgo_up(bp)) = int64(2)
	if libc.Int32FromUint8((*TSessionChange)(unsafe.Pointer(pC)).Fop) == int32(SQLITE_INSERT) {
		if (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid != 0 {
			**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64(9)
		}
		if op != int32(SQLITE_DELETE) {
			ii = 0
			for {
				if !(ii < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
					break
				}
				**(**uintptr)(__ccgo_up(bp + 8)) = uintptr(0)
				(*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxNew})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, **(**int32)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FaiIdx + uintptr(ii)*4)), bp+8)
				_sessionSerializeValue(tls, uintptr(0), **(**uintptr)(__ccgo_up(bp + 8)), bp)
				goto _1
			_1:
				;
				ii = ii + 1
			}
		}
	} else {
		if op == int32(SQLITE_DELETE) {
			**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64((*TSessionChange)(unsafe.Pointer(pC)).FnRecord)
			if Xsqlite3_preupdate_blobwrite(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fdb) >= 0 {
				**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64((*TSessionChange)(unsafe.Pointer(pC)).FnRecord)
			}
		} else {
			pCsr = (*TSessionChange)(unsafe.Pointer(pC)).FaRecord
			if (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid != 0 {
				**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64(libc.Int32FromInt32(9)+libc.Int32FromInt32(1))
				pCsr = pCsr + uintptr(9)
			}
			ii1 = (*TSessionTable)(unsafe.Pointer(pTab)).FbRowid
			for {
				if !(ii1 < (*TSessionTable)(unsafe.Pointer(pTab)).FnCol) {
					break
				}
				bChanged = int32(1)
				nOld = 0
				iIdx = **(**int32)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FaiIdx + uintptr(ii1)*4))
				**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
				(*(*func(*libc.TLS, uintptr, int32, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FxNew})))(tls, (*Tsqlite3_session)(unsafe.Pointer(pSession)).Fhook.FpCtx, iIdx, bp+12)
				if **(**uintptr)(__ccgo_up(bp + 12)) == uintptr(0) {
					return int32(SQLITE_NOMEM)
				}
				v3 = pCsr
				pCsr = pCsr + 1
				eType = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(v3)))
				switch eType {
				case int32(SQLITE_NULL):
					bChanged = libc.BoolInt32(Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(bp + 12))) != int32(SQLITE_NULL))
				case int32(SQLITE_FLOAT):
					fallthrough
				case int32(SQLITE_INTEGER):
					if eType == Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(bp + 12))) {
						**(**Tsqlite3_int64)(__ccgo_up(bp + 16)) = _sessionGetI64(tls, pCsr)
						if eType == int32(SQLITE_INTEGER) {
							bChanged = libc.BoolInt32(**(**Tsqlite3_int64)(__ccgo_up(bp + 16)) != Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(bp + 12))))
						} else {
							libc.Xmemcpy(tls, bp+24, bp+16, uint32(8))
							bChanged = libc.BoolInt32(**(**float64)(__ccgo_up(bp + 24)) != Xsqlite3_value_double(tls, **(**uintptr)(__ccgo_up(bp + 12))))
						}
					}
					nOld = int32(8)
					pCsr = pCsr + uintptr(8)
				default:
					nOld = _sessionVarintGet(tls, pCsr, bp+32)
					pCsr = pCsr + uintptr(nOld)
					nOld = nOld + **(**int32)(__ccgo_up(bp + 32))
					if eType == Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(bp + 12))) && **(**int32)(__ccgo_up(bp + 32)) == Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(bp + 12))) && (**(**int32)(__ccgo_up(bp + 32)) == 0 || 0 == libc.Xmemcmp(tls, pCsr, Xsqlite3_value_blob(tls, **(**uintptr)(__ccgo_up(bp + 12))), libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp + 32))))) {
						bChanged = 0
					}
					pCsr = pCsr + uintptr(**(**int32)(__ccgo_up(bp + 32)))
					break
				}
				if bChanged != 0 && **(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(ii1))) != 0 {
					**(**Ti64)(__ccgo_up(bp)) = int64((*TSessionChange)(unsafe.Pointer(pC)).FnRecord + int32(2))
					break
				}
				if bChanged != 0 {
					**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64(int32(1)+nOld)
					_sessionSerializeValue(tls, uintptr(0), **(**uintptr)(__ccgo_up(bp + 12)), bp)
				} else {
					if **(**Tu8)(__ccgo_up((*TSessionTable)(unsafe.Pointer(pTab)).FabPK + uintptr(ii1))) != 0 {
						**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64(int32(2)+nOld)
					} else {
						**(**Ti64)(__ccgo_up(bp)) = **(**Ti64)(__ccgo_up(bp)) + int64(2)
					}
				}
				goto _2
			_2:
				;
				ii1 = ii1 + 1
			}
		}
	}
	if **(**Ti64)(__ccgo_up(bp)) > int64((*TSessionChange)(unsafe.Pointer(pC)).FnMaxSize) {
		nIncr = int32(**(**Ti64)(__ccgo_up(bp)) - int64((*TSessionChange)(unsafe.Pointer(pC)).FnMaxSize))
		(*TSessionChange)(unsafe.Pointer(pC)).FnMaxSize = int32(**(**Ti64)(__ccgo_up(bp)))
		**(**Ti64)(__ccgo_up(pSession + 48)) += int64(nIncr)
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Session-change object (*pp) contains an old.* record with fewer than
//	** nCol fields. This function updates it with the default values for
//	** the missing fields.
//	*/
func _sessionUpdateOneChange(tls *libc.TLS, pSession uintptr, pRc uintptr, pp uintptr, nCol int32, pDflt uintptr) {
	var eType, iField, n, n1, n2, nByte, nIncr, v1 int32
	var iVal Ti64
	var pNew, pOld, z, z1, v2 uintptr
	var rVal float64
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = eType, iField, iVal, n, n1, n2, nByte, nIncr, pNew, pOld, rVal, z, z1, v1, v2
	pOld = **(**uintptr)(__ccgo_up(pp))
	for libc.Int32FromUint16((*TSessionChange)(unsafe.Pointer(pOld)).FnRecordField) < nCol {
		pNew = uintptr(0)
		nByte = 0
		nIncr = 0
		iField = libc.Int32FromUint16((*TSessionChange)(unsafe.Pointer(pOld)).FnRecordField)
		eType = Xsqlite3_column_type(tls, pDflt, iField)
		switch eType {
		case int32(SQLITE_NULL):
			nIncr = int32(1)
		case int32(SQLITE_INTEGER):
			fallthrough
		case int32(SQLITE_FLOAT):
			nIncr = int32(9)
		default:
			n = Xsqlite3_column_bytes(tls, pDflt, iField)
			nIncr = int32(1) + _sessionVarintLen(tls, n) + n
			break
		}
		nByte = libc.Int32FromUint32(libc.Uint32FromInt32(nIncr) + (uint32(20) + libc.Uint32FromInt32((*TSessionChange)(unsafe.Pointer(pOld)).FnRecord)))
		pNew = _sessionMalloc64(tls, pSession, int64(nByte))
		if pNew == uintptr(0) {
			**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_NOMEM)
			return
		} else {
			libc.Xmemcpy(tls, pNew, pOld, uint32(20))
			(*TSessionChange)(unsafe.Pointer(pNew)).FaRecord = pNew + 1*20
			libc.Xmemcpy(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord, (*TSessionChange)(unsafe.Pointer(pOld)).FaRecord, libc.Uint32FromInt32((*TSessionChange)(unsafe.Pointer(pOld)).FnRecord))
			v2 = pNew + 8
			v1 = *(*int32)(unsafe.Pointer(v2))
			*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
			**(**Tu8)(__ccgo_up((*TSessionChange)(unsafe.Pointer(pNew)).FaRecord + uintptr(v1))) = libc.Uint8FromInt32(eType)
			switch eType {
			case int32(SQLITE_INTEGER):
				iVal = Xsqlite3_column_int64(tls, pDflt, iField)
				_sessionPutI64(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), iVal)
				**(**int32)(__ccgo_up(pNew + 8)) += int32(8)
			case int32(SQLITE_FLOAT):
				rVal = Xsqlite3_column_double(tls, pDflt, iField)
				_sessionPutDouble(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), rVal)
				**(**int32)(__ccgo_up(pNew + 8)) += int32(8)
			case int32(SQLITE_TEXT):
				n1 = Xsqlite3_column_bytes(tls, pDflt, iField)
				z = Xsqlite3_column_text(tls, pDflt, iField)
				**(**int32)(__ccgo_up(pNew + 8)) += _sessionVarintPut(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), n1)
				libc.Xmemcpy(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), z, libc.Uint32FromInt32(n1))
				**(**int32)(__ccgo_up(pNew + 8)) += n1
			case int32(SQLITE_BLOB):
				n2 = Xsqlite3_column_bytes(tls, pDflt, iField)
				z1 = Xsqlite3_column_blob(tls, pDflt, iField)
				**(**int32)(__ccgo_up(pNew + 8)) += _sessionVarintPut(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), n2)
				libc.Xmemcpy(tls, (*TSessionChange)(unsafe.Pointer(pNew)).FaRecord+uintptr((*TSessionChange)(unsafe.Pointer(pNew)).FnRecord), z1, libc.Uint32FromInt32(n2))
				**(**int32)(__ccgo_up(pNew + 8)) += n2
			default:
				break
			}
			_sessionFree(tls, pSession, pOld)
			v2 = pNew
			pOld = v2
			**(**uintptr)(__ccgo_up(pp)) = v2
			(*TSessionChange)(unsafe.Pointer(pNew)).FnRecordField = (*TSessionChange)(unsafe.Pointer(pNew)).FnRecordField + 1
			**(**int32)(__ccgo_up(pNew + 4)) += nIncr
			if pSession != 0 {
				**(**Ti64)(__ccgo_up(pSession + 48)) += int64(nIncr)
			}
		}
	}
}

// C documentation
//
//	/*
//	** This function sets the value of the sqlite3_value object passed as the
//	** first argument to a copy of the string or blob held in the aData[]
//	** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
//	** error occurs.
//	*/
func _sessionValueSetStr(tls *libc.TLS, pVal uintptr, aData uintptr, nData int32, enc Tu8) (r int32) {
	var aCopy uintptr
	_ = aCopy
	/* In theory this code could just pass SQLITE_TRANSIENT as the final
	 ** argument to sqlite3ValueSetStr() and have the copy created
	 ** automatically. But doing so makes it difficult to detect any OOM
	 ** error. Hence the code to create the copy externally. */
	aCopy = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(int64(nData)+int64(1)))
	if aCopy == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemcpy(tls, aCopy, aData, libc.Uint32FromInt32(nData))
	_sqlite3ValueSetStr(tls, pVal, nData, aCopy, enc, __ccgo_fp(Xsqlite3_free))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Read a varint value from buffer aBuf[], size nBuf bytes, into *piVal.
//	** Return the number of bytes read.
//	*/
func _sessionVarintGetSafe(tls *libc.TLS, aBuf uintptr, nBuf int32, piVal uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aRead uintptr
	var v1 int32
	var _ /* aCopy at bp+0 */ [9]Tu8
	_, _ = aRead, v1
	aRead = aBuf
	libc.Xmemset(tls, bp, 0, uint32(9))
	if libc.Uint32FromInt32(nBuf) < uint32(9) {
		libc.Xmemcpy(tls, bp, aBuf, libc.Uint32FromInt32(nBuf))
		aRead = bp
	}
	if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aRead))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
		**(**int32)(__ccgo_up(piVal)) = libc.Int32FromUint32(uint32(**(**Tu8)(__ccgo_up(aRead))))
		v1 = libc.Int32FromInt32(1)
	} else {
		v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aRead, piVal))
	}
	return libc.Int32FromUint8(libc.Uint8FromInt32(v1))
}

/* Load an unaligned and unsigned 32-bit integer */

// C documentation
//
//	/**************************** sqlite3_result_  *******************************
//	** The following routines are used by user-defined functions to specify
//	** the function result.
//	**
//	** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
//	** result as a string or blob.  Appropriate errors are set if the string/blob
//	** is too big or if an OOM occurs.
//	**
//	** The invokeValueDestructor(P,X) routine invokes destructor function X()
//	** on value P if P is not going to be used and need to be destroyed.
//	*/
func _setResultStrOrError(tls *libc.TLS, pCtx uintptr, z uintptr, n int32, enc Tu8, __ccgo_fp_xDel uintptr) {
	var pOut, v1 uintptr
	var rc int32
	_, _, _ = pOut, rc, v1
	pOut = (*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpOut
	if libc.Int32FromUint8(enc) == int32(SQLITE_UTF8) {
		rc = _sqlite3VdbeMemSetText(tls, pOut, z, int64(n), __ccgo_fp_xDel)
	} else {
		if libc.Int32FromUint8(enc) == int32(SQLITE_UTF8_ZT) {
			/* It is usually considered improper to assert() on an input. However,
			 ** the following assert() is checking for inputs that are documented
			 ** to result in undefined behavior. */
			rc = _sqlite3VdbeMemSetText(tls, pOut, z, int64(n), __ccgo_fp_xDel)
			v1 = pOut + 16
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_Term))
		} else {
			rc = _sqlite3VdbeMemSetStr(tls, pOut, z, int64(n), enc, __ccgo_fp_xDel)
		}
	}
	if rc != 0 {
		if rc == int32(SQLITE_TOOBIG) {
			Xsqlite3_result_error_toobig(tls, pCtx)
		} else {
			/* The only errors possible from sqlite3VdbeMemSetStr are
			 ** SQLITE_TOOBIG and SQLITE_NOMEM */
			Xsqlite3_result_error_nomem(tls, pCtx)
		}
		return
	}
	_sqlite3VdbeChangeEncoding(tls, pOut, libc.Int32FromUint8((*Tsqlite3_context)(unsafe.Pointer(pCtx)).Fenc))
	if _sqlite3VdbeMemTooBig(tls, pOut) != 0 {
		Xsqlite3_result_error_toobig(tls, pCtx)
	}
}

// C documentation
//
//	/*
//	** Add a lock on the table with root-page iTable to the shared-btree used
//	** by Btree handle p. Parameter eLock must be either READ_LOCK or
//	** WRITE_LOCK.
//	**
//	** This function assumes the following:
//	**
//	**   (a) The specified Btree object p is connected to a sharable
//	**       database (one with the BtShared.sharable flag set), and
//	**
//	**   (b) No other Btree objects hold a lock that conflicts
//	**       with the requested lock (i.e. querySharedCacheTableLock() has
//	**       already been called and returned SQLITE_OK).
//	**
//	** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
//	** is returned if a malloc attempt fails.
//	*/
func _setSharedCacheTableLock(tls *libc.TLS, p uintptr, iTable TPgno, eLock Tu8) (r int32) {
	var pBt, pIter, pLock uintptr
	_, _, _ = pBt, pIter, pLock
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	pLock = uintptr(0)
	/* A connection with the read-uncommitted flag set will never try to
	 ** obtain a read-lock using this function. The only read-lock obtained
	 ** by a connection in read-uncommitted mode is on the sqlite_schema
	 ** table, and that lock is obtained in BtreeBeginTrans().  */
	/* This function should only be called on a sharable b-tree after it
	 ** has been determined that no other b-tree holds a conflicting lock.  */
	/* First search the list for an existing lock on this table. */
	pIter = (*TBtShared)(unsafe.Pointer(pBt)).FpLock
	for {
		if !(pIter != 0) {
			break
		}
		if (*TBtLock)(unsafe.Pointer(pIter)).FiTable == iTable && (*TBtLock)(unsafe.Pointer(pIter)).FpBtree == p {
			pLock = pIter
			break
		}
		goto _1
	_1:
		;
		pIter = (*TBtLock)(unsafe.Pointer(pIter)).FpNext
	}
	/* If the above search did not find a BtLock struct associating Btree p
	 ** with table iTable, allocate one and link it into the list.
	 */
	if !(pLock != 0) {
		pLock = _sqlite3MallocZero(tls, uint64(16))
		if !(pLock != 0) {
			return int32(SQLITE_NOMEM)
		}
		(*TBtLock)(unsafe.Pointer(pLock)).FiTable = iTable
		(*TBtLock)(unsafe.Pointer(pLock)).FpBtree = p
		(*TBtLock)(unsafe.Pointer(pLock)).FpNext = (*TBtShared)(unsafe.Pointer(pBt)).FpLock
		(*TBtShared)(unsafe.Pointer(pBt)).FpLock = pLock
	}
	/* Set the BtLock.eLock variable to the maximum of the current lock
	 ** and the requested lock. This means if a write-lock was already held
	 ** and a read-lock requested, we don't incorrectly downgrade the lock.
	 */
	if libc.Int32FromUint8(eLock) > libc.Int32FromUint8((*TBtLock)(unsafe.Pointer(pLock)).FeLock) {
		(*TBtLock)(unsafe.Pointer(pLock)).FeLock = eLock
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Set up the lookaside buffers for a database connection.
//	** Return SQLITE_OK on success.
//	** If lookaside is already active, return SQLITE_BUSY.
//	**
//	** The sz parameter is the number of bytes in each lookaside slot.
//	** The cnt parameter is the number of slots.  If pBuf is NULL the
//	** space for the lookaside memory is obtained from sqlite3_malloc()
//	** or similar.  If pBuf is not NULL then it is sz*cnt bytes of memory
//	** to use for the lookaside memory.
//	*/
func _setupLookaside(tls *libc.TLS, db uintptr, pBuf uintptr, sz int32, cnt int32) (r int32) {
	var i, nBig, nSm, v1 int32
	var p, pStart uintptr
	var szAlloc Tsqlite3_int64
	_, _, _, _, _, _, _ = i, nBig, nSm, p, pStart, szAlloc, v1 /* Number smaller LOOKASIDE_SMALL-byte slots */
	if _sqlite3LookasideUsed(tls, db, uintptr(0)) > 0 {
		return int32(SQLITE_BUSY)
	}
	/* Free any existing lookaside buffer for this handle before
	 ** allocating a new one so we don't have to have space for
	 ** both at the same time.
	 */
	if (*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FbMalloced != 0 {
		Xsqlite3_free(tls, (*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpStart)
	}
	/* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
	 ** than a pointer and small enough to fit in a u16.
	 */
	sz = sz & ^libc.Int32FromInt32(7)
	if sz <= libc.Int32FromInt64(4) {
		sz = 0
	}
	if sz > int32(65528) {
		sz = int32(65528)
	}
	/* Count must be at least 1 to be useful, but not so large as to use
	 ** more than 0x7fff0000 total bytes for lookaside. */
	if cnt < int32(1) {
		cnt = 0
	}
	if sz > 0 && cnt > int32(0x7fff0000)/sz {
		cnt = int32(0x7fff0000) / sz
	}
	szAlloc = int64(sz) * int64(cnt)
	if szAlloc == 0 {
		sz = 0
		pStart = uintptr(0)
	} else {
		if pBuf == uintptr(0) {
			_sqlite3BeginBenignMalloc(tls)
			pStart = _sqlite3Malloc(tls, libc.Uint64FromInt64(szAlloc))
			_sqlite3EndBenignMalloc(tls)
			if pStart != 0 {
				szAlloc = int64(_sqlite3MallocSize(tls, pStart))
			}
		} else {
			pStart = pBuf
		}
	}
	if sz >= libc.Int32FromInt32(LOOKASIDE_SMALL)*libc.Int32FromInt32(3) {
		nBig = int32(szAlloc / int64(libc.Int32FromInt32(3)*libc.Int32FromInt32(LOOKASIDE_SMALL)+sz))
		nSm = int32((szAlloc - int64(sz)*int64(nBig)) / int64(LOOKASIDE_SMALL))
	} else {
		if sz >= libc.Int32FromInt32(LOOKASIDE_SMALL)*libc.Int32FromInt32(2) {
			nBig = int32(szAlloc / int64(libc.Int32FromInt32(LOOKASIDE_SMALL)+sz))
			nSm = int32((szAlloc - int64(sz)*int64(nBig)) / int64(LOOKASIDE_SMALL))
		} else {
			if sz > 0 {
				nBig = int32(szAlloc / int64(sz))
				nSm = 0
			} else {
				v1 = libc.Int32FromInt32(0)
				nSm = v1
				nBig = v1
			}
		}
	}
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpStart = pStart
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpInit = uintptr(0)
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpFree = uintptr(0)
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.Fsz = libc.Uint16FromInt32(sz)
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FszTrue = libc.Uint16FromInt32(sz)
	if pStart != 0 {
		p = pStart
		i = 0
		for {
			if !(i < nBig) {
				break
			}
			(*TLookasideSlot)(unsafe.Pointer(p)).FpNext = (*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpInit
			(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpInit = p
			p = p + uintptr(sz)
			goto _2
		_2:
			;
			i = i + 1
		}
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallInit = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallFree = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpMiddle = p
		i = 0
		for {
			if !(i < nSm) {
				break
			}
			(*TLookasideSlot)(unsafe.Pointer(p)).FpNext = (*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallInit
			(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallInit = p
			p = p + 128
			goto _3
		_3:
			;
			i = i + 1
		}
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpEnd = p
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FbDisable = uint32(0)
		if pBuf == uintptr(0) {
			v1 = int32(1)
		} else {
			v1 = 0
		}
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FbMalloced = libc.Uint8FromInt32(v1)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FnSlot = libc.Uint32FromInt32(nBig + nSm)
	} else {
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpStart = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallInit = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpSmallFree = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpMiddle = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpEnd = uintptr(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FbDisable = uint32(1)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.Fsz = uint16(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FbMalloced = uint8(0)
		(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FnSlot = uint32(0)
	}
	(*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpTrueEnd = (*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpEnd
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
//	*/
func _splitNodeStartree(tls *libc.TLS, pRtree uintptr, aCell uintptr, nCell int32, pLeft uintptr, pRight uintptr, pBboxLeft uintptr, pBboxRight uintptr) (r int32) {
	bp := tls.Alloc(96)
	defer tls.Free(96)
	var aSpare, aaSorted, pBbox, pCell, pTarget, v7, v8 uintptr
	var area, fBestArea, fBestMargin, fBestOverlap, margin, overlap TRtreeDValue
	var iBestDim, iBestLeft, iBestSplit, ii, jj, kk, nLeft int32
	var nByte Tsqlite3_int64
	var _ /* left at bp+0 */ TRtreeCell
	var _ /* right at bp+48 */ TRtreeCell
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aSpare, aaSorted, area, fBestArea, fBestMargin, fBestOverlap, iBestDim, iBestLeft, iBestSplit, ii, jj, kk, margin, nByte, nLeft, overlap, pBbox, pCell, pTarget, v7, v8
	iBestDim = 0
	iBestSplit = 0
	fBestMargin = float64(0)
	nByte = libc.Int64FromUint32(libc.Uint32FromInt32(libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim)+libc.Int32FromInt32(1)) * (uint32(4) + libc.Uint32FromInt32(nCell)*uint32(4)))
	aaSorted = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
	if !(aaSorted != 0) {
		return int32(SQLITE_NOMEM)
	}
	aSpare = aaSorted + uintptr((*TRtree)(unsafe.Pointer(pRtree)).FnDim)*4 + uintptr(libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim)*nCell)*4
	libc.Xmemset(tls, aaSorted, 0, libc.Uint32FromInt64(nByte))
	ii = 0
	for {
		if !(ii < libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim)) {
			break
		}
		**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)) = aaSorted + uintptr((*TRtree)(unsafe.Pointer(pRtree)).FnDim)*4 + uintptr(ii*nCell)*4
		jj = 0
		for {
			if !(jj < nCell) {
				break
			}
			**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)) + uintptr(jj)*4)) = jj
			goto _2
		_2:
			;
			jj = jj + 1
		}
		_SortByDimension(tls, pRtree, **(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)), nCell, ii, aCell, aSpare)
		goto _1
	_1:
		;
		ii = ii + 1
	}
	ii = 0
	for {
		if !(ii < libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnDim)) {
			break
		}
		margin = float64(0)
		fBestOverlap = float64(0)
		fBestArea = float64(0)
		iBestLeft = 0
		nLeft = ((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize - int32(4)) / libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell) / int32(3)
		for {
			if !(nLeft <= nCell-((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize-int32(4))/libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell)/int32(3)) {
				break
			}
			libc.Xmemcpy(tls, bp, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)))))*48, uint32(48))
			libc.Xmemcpy(tls, bp+48, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)) + uintptr(nCell-int32(1))*4)))*48, uint32(48))
			kk = int32(1)
			for {
				if !(kk < nCell-int32(1)) {
					break
				}
				if kk < nLeft {
					_cellUnion(tls, pRtree, bp, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)) + uintptr(kk)*4)))*48)
				} else {
					_cellUnion(tls, pRtree, bp+48, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(ii)*4)) + uintptr(kk)*4)))*48)
				}
				goto _5
			_5:
				;
				kk = kk + 1
			}
			margin = margin + _cellMargin(tls, pRtree, bp)
			margin = margin + _cellMargin(tls, pRtree, bp+48)
			overlap = _cellOverlap(tls, pRtree, bp, bp+48, int32(1))
			area = _cellArea(tls, pRtree, bp) + _cellArea(tls, pRtree, bp+48)
			if nLeft == ((*TRtree)(unsafe.Pointer(pRtree)).FiNodeSize-int32(4))/libc.Int32FromUint8((*TRtree)(unsafe.Pointer(pRtree)).FnBytesPerCell)/int32(3) || overlap < fBestOverlap || overlap == fBestOverlap && area < fBestArea {
				iBestLeft = nLeft
				fBestOverlap = overlap
				fBestArea = area
			}
			goto _4
		_4:
			;
			nLeft = nLeft + 1
		}
		if ii == 0 || margin < fBestMargin {
			iBestDim = ii
			fBestMargin = margin
			iBestSplit = iBestLeft
		}
		goto _3
	_3:
		;
		ii = ii + 1
	}
	libc.Xmemcpy(tls, pBboxLeft, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(iBestDim)*4)))))*48, uint32(48))
	libc.Xmemcpy(tls, pBboxRight, aCell+uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(iBestDim)*4)) + uintptr(iBestSplit)*4)))*48, uint32(48))
	ii = 0
	for {
		if !(ii < nCell) {
			break
		}
		if ii < iBestSplit {
			v7 = pLeft
		} else {
			v7 = pRight
		}
		pTarget = v7
		if ii < iBestSplit {
			v8 = pBboxLeft
		} else {
			v8 = pBboxRight
		}
		pBbox = v8
		pCell = aCell + uintptr(**(**int32)(__ccgo_up(**(**uintptr)(__ccgo_up(aaSorted + uintptr(iBestDim)*4)) + uintptr(ii)*4)))*48
		_nodeInsertCell(tls, pRtree, pTarget, pCell)
		_cellUnion(tls, pRtree, pBbox, pCell)
		goto _6
	_6:
		;
		ii = ii + 1
	}
	Xsqlite3_free(tls, aaSorted)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Set the collation function of the most recently parsed table column
//	** to the CollSeq given.
//	*/
func _sqlite3AddCollateType(tls *libc.TLS, pParse uintptr, pToken uintptr) {
	var db, p, pIdx, zColl, v1 uintptr
	var i int32
	_, _, _, _, _, _ = db, i, p, pIdx, zColl, v1
	v1 = (*TParse)(unsafe.Pointer(pParse)).FpNewTable
	p = v1
	if v1 == uintptr(0) || libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) >= int32(PARSE_MODE_RENAME) {
		return
	}
	i = int32((*TTable)(unsafe.Pointer(p)).FnCol) - int32(1)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	zColl = _sqlite3NameFromToken(tls, db, pToken)
	if !(zColl != 0) {
		return
	}
	if _sqlite3LocateCollSeq(tls, pParse, zColl) != 0 {
		_sqlite3ColumnSetColl(tls, db, (*TTable)(unsafe.Pointer(p)).FaCol+uintptr(i)*12, zColl)
		/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
		 ** then an index may have been created on this column before the
		 ** collation type was added. Correct this if it is the case.
		 */
		pIdx = (*TTable)(unsafe.Pointer(p)).FpIndex
		for {
			if !(pIdx != 0) {
				break
			}
			if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn))) == i {
				**(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FazColl)) = _sqlite3ColumnColl(tls, (*TTable)(unsafe.Pointer(p)).FaCol+uintptr(i)*12)
			}
			goto _2
		_2:
			;
			pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		}
	}
	_sqlite3DbFree(tls, db, zColl)
}

// C documentation
//
//	/*
//	** This routine is called by the parser while in the middle of
//	** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
//	** been seen on a column.  This routine sets the notNull flag on
//	** the column currently under construction.
//	*/
func _sqlite3AddNotNull(tls *libc.TLS, pParse uintptr, onError int32) {
	var p, pCol, pIdx uintptr
	_, _, _ = p, pCol, pIdx
	p = (*TParse)(unsafe.Pointer(pParse)).FpNewTable
	if p == uintptr(0) || int32((*TTable)(unsafe.Pointer(p)).FnCol) < int32(1) {
		return
	}
	pCol = (*TTable)(unsafe.Pointer(p)).FaCol + uintptr(int32((*TTable)(unsafe.Pointer(p)).FnCol)-int32(1))*12
	libc.SetBitFieldPtr8Uint32(pCol+4, uint32(libc.Uint8FromInt32(onError)), 0, 0xf)
	**(**Tu32)(__ccgo_up(p + 28)) |= uint32(TF_HasNotNull)
	/* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
	 ** on this column.  */
	if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FcolFlags)&int32(COLFLAG_UNIQUE) != 0 {
		pIdx = (*TTable)(unsafe.Pointer(p)).FpIndex
		for {
			if !(pIdx != 0) {
				break
			}
			if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn))) == int32((*TTable)(unsafe.Pointer(p)).FnCol)-int32(1) {
				libc.SetBitFieldPtr16Uint32(pIdx+56, libc.Uint32FromInt32(1), 3, 0x8)
			}
			goto _1
		_1:
			;
			pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		}
	}
}

// C documentation
//
//	/*
//	** Register built-in functions used to help implement ALTER TABLE
//	*/
func _sqlite3AlterFunctions(tls *libc.TLS) {
	_sqlite3InsertBuiltinFuncs(tls, uintptr(unsafe.Pointer(&_aAlterTableFuncs)), libc.Int32FromUint32(libc.Uint32FromInt64(360)/libc.Uint32FromInt64(40)))
}

// C documentation
//
//	/*
//	** Generate code for the ANALYZE command.  The parser calls this routine
//	** when it recognizes an ANALYZE command.
//	**
//	**        ANALYZE                            -- 1
//	**        ANALYZE  <database>                -- 2
//	**        ANALYZE  ?<database>.?<tablename>  -- 3
//	**
//	** Form 1 causes all indices in all attached databases to be analyzed.
//	** Form 2 analyzes all indices the single database named.
//	** Form 3 analyzes all indices associated with the named table.
//	*/
func _sqlite3Analyze(tls *libc.TLS, pParse uintptr, pName1 uintptr, pName2 uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, pIdx, pTab, v, z, zDb, v4 uintptr
	var i, iDb, v2 int32
	var v3 bool
	var _ /* pTableName at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _ = db, i, iDb, pIdx, pTab, v, z, zDb, v2, v3, v4
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	/* Read the database schema. If an error occurs, leave an error message
	 ** and code in pParse and return NULL. */
	if SQLITE_OK != _sqlite3ReadSchema(tls, pParse) {
		return
	}
	if pName1 == uintptr(0) {
		/* Form 1:  Analyze everything */
		i = 0
		for {
			if !(i < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
				break
			}
			if i == int32(1) {
				goto _1
			} /* Do not analyze the TEMP database */
			_analyzeDatabase(tls, pParse, i)
			goto _1
		_1:
			;
			i = i + 1
		}
	} else {
		if v3 = (*TToken)(unsafe.Pointer(pName2)).Fn == uint32(0); v3 {
			v2 = _sqlite3FindDb(tls, db, pName1)
			iDb = v2
		}
		if v3 && v2 >= 0 {
			/* Analyze the schema named as the argument */
			_analyzeDatabase(tls, pParse, iDb)
		} else {
			/* Form 3: Analyze the table or index named as an argument */
			iDb = _sqlite3TwoPartName(tls, pParse, pName1, pName2, bp)
			if iDb >= 0 {
				if (*TToken)(unsafe.Pointer(pName2)).Fn != 0 {
					v4 = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName
				} else {
					v4 = uintptr(0)
				}
				zDb = v4
				z = _sqlite3NameFromToken(tls, db, **(**uintptr)(__ccgo_up(bp)))
				if z != 0 {
					v4 = _sqlite3FindIndex(tls, db, z, zDb)
					pIdx = v4
					if v4 != uintptr(0) {
						_analyzeTable(tls, pParse, (*TIndex)(unsafe.Pointer(pIdx)).FpTable, pIdx)
					} else {
						v4 = _sqlite3LocateTable(tls, pParse, uint32(0), z, zDb)
						pTab = v4
						if v4 != uintptr(0) {
							_analyzeTable(tls, pParse, pTab, uintptr(0))
						}
					}
					_sqlite3DbFree(tls, db, z)
				}
			}
		}
	}
	if v3 = libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FnSqlExec) == 0; v3 {
		v4 = _sqlite3GetVdbe(tls, pParse)
		v = v4
	}
	if v3 && v4 != uintptr(0) {
		_sqlite3VdbeAddOp0(tls, v, int32(OP_Expire))
	}
}

// C documentation
//
//	/*
//	** pArray is a pointer to an array of objects. Each object in the
//	** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
//	** to extend the array so that there is space for a new object at the end.
//	**
//	** When this function is called, *pnEntry contains the current size of
//	** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
//	** in total).
//	**
//	** If the realloc() is successful (i.e. if no OOM condition occurs), the
//	** space allocated for the new object is zeroed, *pnEntry updated to
//	** reflect the new size of the array and a pointer to the new allocation
//	** returned. *pIdx is set to the index of the new array entry in this case.
//	**
//	** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
//	** unchanged and a copy of pArray returned.
//	*/
func _sqlite3ArrayAllocate(tls *libc.TLS, db uintptr, pArray uintptr, szEntry int32, pnEntry uintptr, pIdx uintptr) (r uintptr) {
	var n, sz Tsqlite3_int64
	var pNew, z uintptr
	var v1 int32
	var v2 int64
	_, _, _, _, _, _ = n, pNew, sz, z, v1, v2
	v1 = **(**int32)(__ccgo_up(pnEntry))
	**(**int32)(__ccgo_up(pIdx)) = v1
	n = int64(v1)
	if n&(n-int64(1)) == 0 {
		if n == 0 {
			v2 = int64(1)
		} else {
			v2 = int64(2) * n
		}
		sz = v2
		pNew = _sqlite3DbRealloc(tls, db, pArray, libc.Uint64FromInt64(sz*int64(szEntry)))
		if pNew == uintptr(0) {
			**(**int32)(__ccgo_up(pIdx)) = -int32(1)
			return pArray
		}
		pArray = pNew
	}
	z = pArray
	libc.Xmemset(tls, z+uintptr(n*int64(szEntry)), 0, libc.Uint32FromInt32(szEntry))
	**(**int32)(__ccgo_up(pnEntry)) = **(**int32)(__ccgo_up(pnEntry)) + 1
	return pArray
}

// C documentation
//
//	/*
//	** This routine generates code that will initialize all of the
//	** register used by the autoincrement tracker.
//	*/
func _sqlite3AutoincrementBegin(tls *libc.TLS, pParse uintptr) {
	var aOp, db, p, pDb, v uintptr
	var memId int32
	_, _, _, _, _, _ = aOp, db, memId, p, pDb, v /* Information about an AUTOINCREMENT */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb   /* Register holding max rowid */
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe /* VDBE under construction */
	/* This routine is never called during trigger-generation.  It is
	 ** only called from the top-level */
	/* We failed long ago if this is not so */
	p = (*TParse)(unsafe.Pointer(pParse)).FpAinc
	for {
		if !(p != 0) {
			break
		}
		pDb = (*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr((*TAutoincInfo)(unsafe.Pointer(p)).FiDb)*16
		memId = (*TAutoincInfo)(unsafe.Pointer(p)).FregCtr
		_sqlite3OpenTable(tls, pParse, 0, (*TAutoincInfo)(unsafe.Pointer(p)).FiDb, (*TSchema)(unsafe.Pointer((*TDb)(unsafe.Pointer(pDb)).FpSchema)).FpSeqTab, int32(OP_OpenRead))
		_sqlite3VdbeLoadString(tls, v, memId-int32(1), (*TTable)(unsafe.Pointer((*TAutoincInfo)(unsafe.Pointer(p)).FpTab)).FzName)
		aOp = _sqlite3VdbeAddOpList(tls, v, libc.Int32FromUint32(libc.Uint32FromInt64(48)/libc.Uint32FromInt64(4)), uintptr(unsafe.Pointer(&_autoInc)), _iLn1)
		if aOp == uintptr(0) {
			break
		}
		(**(**TVdbeOp)(__ccgo_up(aOp))).Fp2 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp))).Fp3 = memId + int32(2)
		(**(**TVdbeOp)(__ccgo_up(aOp + 2*20))).Fp3 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp1 = memId - int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp3 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp + 3*20))).Fp5 = uint16(SQLITE_JUMPIFNULL)
		(**(**TVdbeOp)(__ccgo_up(aOp + 4*20))).Fp2 = memId + int32(1)
		(**(**TVdbeOp)(__ccgo_up(aOp + 5*20))).Fp3 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp + 6*20))).Fp1 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp + 7*20))).Fp2 = memId + int32(2)
		(**(**TVdbeOp)(__ccgo_up(aOp + 7*20))).Fp1 = memId
		(**(**TVdbeOp)(__ccgo_up(aOp + 10*20))).Fp2 = memId
		if (*TParse)(unsafe.Pointer(pParse)).FnTab == 0 {
			(*TParse)(unsafe.Pointer(pParse)).FnTab = int32(1)
		}
		goto _1
	_1:
		;
		p = (*TAutoincInfo)(unsafe.Pointer(p)).FpNext
	}
}

// C documentation
//
//	/*
//	** Clear the i-th bit.
//	**
//	** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
//	** that BitvecClear can use to rebuilt its hash table.
//	*/
func _sqlite3BitvecClear(tls *libc.TLS, p uintptr, i Tu32, pBuf uintptr) {
	var aiValues, v1 uintptr
	var bin, h Tu32
	var j uint32
	_, _, _, _, _ = aiValues, bin, h, j, v1
	if p == uintptr(0) {
		return
	}
	i = i - 1
	for (*TBitvec)(unsafe.Pointer(p)).FiDivisor != 0 {
		bin = i / (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		i = i % (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		p = **(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4))
		if !(p != 0) {
			return
		}
	}
	if (*TBitvec)(unsafe.Pointer(p)).FiSize <= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(1)*libc.Uint32FromInt32(BITVEC_SZELEM) {
		v1 = p + 12 + uintptr(i/uint32(BITVEC_SZELEM))
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^libc.Int32FromUint8(libc.Uint8FromInt32(libc.Int32FromInt32(1)<<(i&libc.Uint32FromInt32(libc.Int32FromInt32(BITVEC_SZELEM)-libc.Int32FromInt32(1))))))
	} else {
		aiValues = pBuf
		libc.Xmemcpy(tls, aiValues, p+12, uint32(500))
		libc.Xmemset(tls, p+12, 0, uint32(500))
		(*TBitvec)(unsafe.Pointer(p)).FnSet = uint32(0)
		j = uint32(0)
		for {
			if !(j < (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4)) {
				break
			}
			if **(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4)) != 0 && **(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4)) != i+uint32(1) {
				h = (**(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4)) - libc.Uint32FromInt32(1)) * libc.Uint32FromInt32(1) % ((libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(4))
				(*TBitvec)(unsafe.Pointer(p)).FnSet = (*TBitvec)(unsafe.Pointer(p)).FnSet + 1
				for **(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) != 0 {
					h = h + 1
					if h >= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4) {
						h = uint32(0)
					}
				}
				**(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) = **(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4))
			}
			goto _2
		_2:
			;
			j = j + 1
		}
	}
}

// C documentation
//
//	/*
//	** Set the i-th bit.  Return 0 on success and an error code if
//	** anything goes wrong.
//	**
//	** This routine might cause sub-bitmaps to be allocated.  Failing
//	** to get the memory needed to hold the sub-bitmap is the only
//	** that can go wrong with an insert, assuming p and i are valid.
//	**
//	** The calling function must ensure that p is a valid Bitvec object
//	** and that the value for "i" is within range of the Bitvec object.
//	** Otherwise the behavior is undefined.
//	*/
func _sqlite3BitvecSet(tls *libc.TLS, p uintptr, i Tu32) (r int32) {
	var aiValues, v1 uintptr
	var bin, h, v2 Tu32
	var j uint32
	var rc int32
	_, _, _, _, _, _, _ = aiValues, bin, h, j, rc, v1, v2
	if p == uintptr(0) {
		return SQLITE_OK
	}
	i = i - 1
	for (*TBitvec)(unsafe.Pointer(p)).FiSize > (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(1)*libc.Uint32FromInt32(BITVEC_SZELEM) && (*TBitvec)(unsafe.Pointer(p)).FiDivisor != 0 {
		bin = i / (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		i = i % (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		if **(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4)) == uintptr(0) {
			**(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4)) = _sqlite3BitvecCreate(tls, (*TBitvec)(unsafe.Pointer(p)).FiDivisor)
			if **(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4)) == uintptr(0) {
				return int32(SQLITE_NOMEM)
			}
		}
		p = **(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4))
	}
	if (*TBitvec)(unsafe.Pointer(p)).FiSize <= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(1)*libc.Uint32FromInt32(BITVEC_SZELEM) {
		v1 = p + 12 + uintptr(i/uint32(BITVEC_SZELEM))
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(1)<<(i&libc.Uint32FromInt32(libc.Int32FromInt32(BITVEC_SZELEM)-libc.Int32FromInt32(1))))
		return SQLITE_OK
	}
	v2 = i
	i = i + 1
	h = v2 * libc.Uint32FromInt32(1) % ((libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(4))
	/* if there wasn't a hash collision, and this doesn't */
	/* completely fill the hash, then just add it without */
	/* worrying about sub-dividing and re-hashing. */
	if !(**(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) != 0) {
		if (*TBitvec)(unsafe.Pointer(p)).FnSet < (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4)-libc.Uint32FromInt32(1) {
			goto bitvec_set_end
		} else {
			goto bitvec_set_rehash
		}
	}
	/* there was a collision, check to see if it's already */
	/* in hash, if not, try to find a spot for it */
	for cond := true; cond; cond = **(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) != 0 {
		if **(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) == i {
			return SQLITE_OK
		}
		h = h + 1
		if h >= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4) {
			h = uint32(0)
		}
	}
	/* we didn't find it in the hash.  h points to the first */
	/* available free spot. check to see if this is going to */
	/* make our hash too "full".  */
	goto bitvec_set_rehash
bitvec_set_rehash:
	;
	if (*TBitvec)(unsafe.Pointer(p)).FnSet >= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4)/libc.Uint32FromInt32(2) {
		aiValues = _sqlite3DbMallocRaw(tls, uintptr(0), uint64(500))
		if aiValues == uintptr(0) {
			return int32(SQLITE_NOMEM)
		} else {
			libc.Xmemcpy(tls, aiValues, p+12, uint32(500))
			libc.Xmemset(tls, p+12, 0, uint32(500))
			(*TBitvec)(unsafe.Pointer(p)).FiDivisor = (*TBitvec)(unsafe.Pointer(p)).FiSize / ((libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(4))
			if (*TBitvec)(unsafe.Pointer(p)).FiSize%((libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4)) != uint32(0) {
				(*TBitvec)(unsafe.Pointer(p)).FiDivisor = (*TBitvec)(unsafe.Pointer(p)).FiDivisor + 1
			}
			if (*TBitvec)(unsafe.Pointer(p)).FiDivisor < (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(1)*libc.Uint32FromInt32(BITVEC_SZELEM) {
				(*TBitvec)(unsafe.Pointer(p)).FiDivisor = (libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(1) * libc.Uint32FromInt32(BITVEC_SZELEM)
			}
			rc = _sqlite3BitvecSet(tls, p, i)
			j = uint32(0)
			for {
				if !(j < (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(4)) {
					break
				}
				if **(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4)) != 0 {
					rc = rc | _sqlite3BitvecSet(tls, p, **(**Tu32)(__ccgo_up(aiValues + uintptr(j)*4)))
				}
				goto _3
			_3:
				;
				j = j + 1
			}
			_sqlite3DbFree(tls, uintptr(0), aiValues)
			return rc
		}
	}
	goto bitvec_set_end
bitvec_set_end:
	;
	(*TBitvec)(unsafe.Pointer(p)).FnSet = (*TBitvec)(unsafe.Pointer(p)).FnSet + 1
	**(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) = i
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Check to see if the i-th bit is set.  Return true or false.
//	** If p is NULL (if the bitmap has not been created) or if
//	** i is out of range, then return false.
//	*/
func _sqlite3BitvecTestNotNull(tls *libc.TLS, p uintptr, i Tu32) (r int32) {
	var bin, h, v1 Tu32
	_, _, _ = bin, h, v1
	i = i - 1
	if i >= (*TBitvec)(unsafe.Pointer(p)).FiSize {
		return 0
	}
	for (*TBitvec)(unsafe.Pointer(p)).FiDivisor != 0 {
		bin = i / (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		i = i % (*TBitvec)(unsafe.Pointer(p)).FiDivisor
		p = **(**uintptr)(__ccgo_up(p + 12 + uintptr(bin)*4))
		if !(p != 0) {
			return 0
		}
	}
	if (*TBitvec)(unsafe.Pointer(p)).FiSize <= (libc.Uint32FromInt32(BITVEC_SZ)-libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4))/libc.Uint32FromInt64(4)*libc.Uint32FromInt64(4)/libc.Uint32FromInt64(1)*libc.Uint32FromInt32(BITVEC_SZELEM) {
		return libc.BoolInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(p + 12 + uintptr(i/uint32(BITVEC_SZELEM)))))&(int32(1)<<(i&libc.Uint32FromInt32(libc.Int32FromInt32(BITVEC_SZELEM)-libc.Int32FromInt32(1)))) != 0)
	} else {
		v1 = i
		i = i + 1
		h = v1 * libc.Uint32FromInt32(1) % ((libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(4))
		for **(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) != 0 {
			if **(**Tu32)(__ccgo_up(p + 12 + uintptr(h)*4)) == i {
				return int32(1)
			}
			h = (h + uint32(1)) % ((libc.Uint32FromInt32(BITVEC_SZ) - libc.Uint32FromInt32(3)*libc.Uint32FromInt64(4)) / libc.Uint32FromInt64(4) * libc.Uint32FromInt64(4) / libc.Uint32FromInt64(4))
		}
		return 0
	}
	return r
}

// C documentation
//
//	/*
//	** Compare two blobs.  Return negative, zero, or positive if the first
//	** is less than, equal to, or greater than the second, respectively.
//	** If one blob is a prefix of the other, then the shorter is the lessor.
//	*/
func _sqlite3BlobCompare(tls *libc.TLS, pB1 uintptr, pB2 uintptr) (r int32) {
	var c, n1, n2, v1 int32
	_, _, _, _ = c, n1, n2, v1
	n1 = (*TMem)(unsafe.Pointer(pB1)).Fn
	n2 = (*TMem)(unsafe.Pointer(pB2)).Fn
	/* It is possible to have a Blob value that has some non-zero content
	 ** followed by zero content.  But that only comes up for Blobs formed
	 ** by the OP_MakeRecord opcode, and such Blobs never get passed into
	 ** sqlite3MemCompare(). */
	if (libc.Int32FromUint16((*TMem)(unsafe.Pointer(pB1)).Fflags)|libc.Int32FromUint16((*TMem)(unsafe.Pointer(pB2)).Fflags))&int32(MEM_Zero) != 0 {
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pB1)).Fflags)&libc.Int32FromUint16((*TMem)(unsafe.Pointer(pB2)).Fflags)&int32(MEM_Zero) != 0 {
			return *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pB1)).Fu)) - *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pB2)).Fu))
		} else {
			if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pB1)).Fflags)&int32(MEM_Zero) != 0 {
				if !(_isAllZero(tls, (*TMem)(unsafe.Pointer(pB2)).Fz, (*TMem)(unsafe.Pointer(pB2)).Fn) != 0) {
					return -int32(1)
				}
				return *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pB1)).Fu)) - n2
			} else {
				if !(_isAllZero(tls, (*TMem)(unsafe.Pointer(pB1)).Fz, (*TMem)(unsafe.Pointer(pB1)).Fn) != 0) {
					return +libc.Int32FromInt32(1)
				}
				return n1 - *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pB2)).Fu))
			}
		}
	}
	if n1 > n2 {
		v1 = n2
	} else {
		v1 = n1
	}
	c = libc.Xmemcmp(tls, (*TMem)(unsafe.Pointer(pB1)).Fz, (*TMem)(unsafe.Pointer(pB2)).Fz, libc.Uint32FromInt32(v1))
	if c != 0 {
		return c
	}
	return n1 - n2
}

/* The following two functions are used only within testcase() to prove
** test coverage.  These functions do no exist for production builds.
** We must use separate SQLITE_NOINLINE functions here, since otherwise
** optimizer code movement causes gcov to become very confused.
 */

// C documentation
//
//	/*
//	** Copy the complete content of pBtFrom into pBtTo.  A transaction
//	** must be active for both files.
//	**
//	** The size of file pTo may be reduced by this operation. If anything
//	** goes wrong, the transaction on pTo is rolled back. If successful, the
//	** transaction is committed before returning.
//	*/
func _sqlite3BtreeCopyFile(tls *libc.TLS, pTo uintptr, pFrom uintptr) (r int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var pFd, v1 uintptr
	var rc int32
	var _ /* b at bp+0 */ Tsqlite3_backup
	var _ /* nByte at bp+56 */ Ti64
	_, _, _ = pFd, rc, v1
	_sqlite3BtreeEnter(tls, pTo)
	_sqlite3BtreeEnter(tls, pFrom)
	pFd = _sqlite3PagerFile(tls, _sqlite3BtreePager(tls, pTo))
	if (*Tsqlite3_file)(unsafe.Pointer(pFd)).FpMethods != 0 {
		**(**Ti64)(__ccgo_up(bp + 56)) = int64(_sqlite3BtreeGetPageSize(tls, pFrom)) * libc.Int64FromUint32(_sqlite3BtreeLastPage(tls, pFrom))
		rc = _sqlite3OsFileControl(tls, pFd, int32(SQLITE_FCNTL_OVERWRITE), bp+56)
		if rc == int32(SQLITE_NOTFOUND) {
			rc = SQLITE_OK
		}
		if rc != 0 {
			goto copy_finished
		}
	}
	/* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
	 ** to 0. This is used by the implementations of sqlite3_backup_step()
	 ** and sqlite3_backup_finish() to detect that they are being called
	 ** from this function, not directly by the user.
	 */
	libc.Xmemset(tls, bp, 0, uint32(52))
	(**(**Tsqlite3_backup)(__ccgo_up(bp))).FpSrcDb = (*TBtree)(unsafe.Pointer(pFrom)).Fdb
	(**(**Tsqlite3_backup)(__ccgo_up(bp))).FpSrc = pFrom
	(**(**Tsqlite3_backup)(__ccgo_up(bp))).FpDest = pTo
	(**(**Tsqlite3_backup)(__ccgo_up(bp))).FiNext = uint32(1)
	/* 0x7FFFFFFF is the hard limit for the number of pages in a database
	 ** file. By passing this as the number of pages to copy to
	 ** sqlite3_backup_step(), we can guarantee that the copy finishes
	 ** within a single call (unless an error occurs). The assert() statement
	 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
	 ** or an error code.  */
	Xsqlite3_backup_step(tls, bp, int32(0x7FFFFFFF))
	rc = Xsqlite3_backup_finish(tls, bp)
	if rc == SQLITE_OK {
		v1 = (*TBtree)(unsafe.Pointer(pTo)).FpBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_PAGESIZE_FIXED))
	} else {
		_sqlite3PagerClearCache(tls, _sqlite3BtreePager(tls, (**(**Tsqlite3_backup)(__ccgo_up(bp))).FpDest))
	}
	goto copy_finished
copy_finished:
	;
	_sqlite3BtreeLeave(tls, pFrom)
	_sqlite3BtreeLeave(tls, pTo)
	return rc
}

/************** End of backup.c **********************************************/
/************** Begin file vdbemem.c *****************************************/
/*
** 2004 May 26
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to manipulate "Mem" structure.  A "Mem"
** stores a single value in the VDBE.  Mem is an opaque structure visible
** only within the VDBE.  Interface routines refer to a Mem using the
** name sqlite_value
 */
/* #include "sqliteInt.h" */
/* #include "vdbeInt.h" */

/* True if X is a power of two.  0 is considered a power of two here.
** In other words, return true if X has at most one bit set.
 */

// C documentation
//
//	/*
//	** Return the offset into the database file for the start of the
//	** payload to which the cursor is pointing.
//	*/
func _sqlite3BtreeOffset(tls *libc.TLS, pCur uintptr) (r Ti64) {
	_getCellInfo(tls, pCur)
	return libc.Int64FromUint32((*TBtShared)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpBt)).FpageSize)*(libc.Int64FromUint32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).Fpgno)-int64(1)) + int64(int32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FpPayload)-int32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FaData))
}

// C documentation
//
//	/*
//	** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
//	**
//	**    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
//	**    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
//	**    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
//	**    newFlag==(-1)    No changes
//	**
//	** This routine acts as a query if newFlag is less than zero
//	**
//	** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
//	** freelist leaf pages are not written back to the database.  Thus in-page
//	** deleted content is cleared, but freelist deleted content is not.
//	**
//	** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
//	** that freelist leaf pages are written back into the database, increasing
//	** the amount of disk I/O.
//	*/
func _sqlite3BtreeSecureDelete(tls *libc.TLS, p uintptr, newFlag int32) (r int32) {
	var b int32
	var v1 uintptr
	_, _ = b, v1
	if p == uintptr(0) {
		return 0
	}
	_sqlite3BtreeEnter(tls, p)
	if newFlag >= 0 {
		v1 = (*TBtree)(unsafe.Pointer(p)).FpBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_FAST_SECURE))
		v1 = (*TBtree)(unsafe.Pointer(p)).FpBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromUint16(libc.Uint16FromInt32(libc.Int32FromInt32(BTS_SECURE_DELETE)*newFlag)))
	}
	b = libc.Int32FromUint16((*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).FpBt)).FbtsFlags) & int32(BTS_FAST_SECURE) / int32(BTS_SECURE_DELETE)
	_sqlite3BtreeLeave(tls, p)
	return b
}

// C documentation
//
//	/*
//	** Change the default pages size and the number of reserved bytes per page.
//	** Or, if the page size has already been fixed, return SQLITE_READONLY
//	** without changing anything.
//	**
//	** The page size must be a power of 2 between 512 and 65536.  If the page
//	** size supplied does not meet this constraint then the page size is not
//	** changed.
//	**
//	** Page sizes are constrained to be a power of two so that the region
//	** of the database file used for locking (beginning at PENDING_BYTE,
//	** the first byte past the 1GB boundary, 0x40000000) needs to occur
//	** at the beginning of a page.
//	**
//	** If parameter nReserve is less than zero, then the number of reserved
//	** bytes per page is left unchanged.
//	**
//	** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
//	** and autovacuum mode can no longer be changed.
//	*/
func _sqlite3BtreeSetPageSize(tls *libc.TLS, p uintptr, pageSize int32, nReserve int32, iFix int32) (r int32) {
	var pBt, v1 uintptr
	var rc, x int32
	_, _, _, _ = pBt, rc, x, v1
	rc = SQLITE_OK
	pBt = (*TBtree)(unsafe.Pointer(p)).FpBt
	_sqlite3BtreeEnter(tls, p)
	(*TBtShared)(unsafe.Pointer(pBt)).FnReserveWanted = libc.Uint8FromInt32(nReserve)
	x = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer(pBt)).FpageSize - (*TBtShared)(unsafe.Pointer(pBt)).FusableSize)
	if x == nReserve && (pageSize == 0 || libc.Uint32FromInt32(pageSize) == (*TBtShared)(unsafe.Pointer(pBt)).FpageSize) {
		_sqlite3BtreeLeave(tls, p)
		return SQLITE_OK
	}
	if nReserve < x {
		nReserve = x
	}
	if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_PAGESIZE_FIXED) != 0 {
		_sqlite3BtreeLeave(tls, p)
		return int32(SQLITE_READONLY)
	}
	if pageSize >= int32(512) && pageSize <= int32(SQLITE_MAX_PAGE_SIZE) && (pageSize-int32(1))&pageSize == 0 {
		if nReserve > int32(32) && pageSize == int32(512) {
			pageSize = int32(1024)
		}
		(*TBtShared)(unsafe.Pointer(pBt)).FpageSize = libc.Uint32FromInt32(pageSize)
		_freeTempSpace(tls, pBt)
	}
	rc = _sqlite3PagerSetPagesize(tls, (*TBtShared)(unsafe.Pointer(pBt)).FpPager, pBt+36, nReserve)
	(*TBtShared)(unsafe.Pointer(pBt)).FusableSize = (*TBtShared)(unsafe.Pointer(pBt)).FpageSize - uint32(libc.Uint16FromInt32(nReserve))
	if iFix != 0 {
		v1 = pBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTS_PAGESIZE_FIXED))
	}
	_sqlite3BtreeLeave(tls, p)
	return rc
}

// C documentation
//
//	/*
//	** Set both the "read version" (single byte at byte offset 18) and
//	** "write version" (single byte at byte offset 19) fields in the database
//	** header to iVersion.
//	*/
func _sqlite3BtreeSetVersion(tls *libc.TLS, pBtree uintptr, iVersion int32) (r int32) {
	var aData, pBt, v1 uintptr
	var rc int32
	_, _, _, _ = aData, pBt, rc, v1
	pBt = (*TBtree)(unsafe.Pointer(pBtree)).FpBt /* Return code */
	/* If setting the version fields to 1, do not automatically open the
	 ** WAL connection, even if the version fields are currently set to 2.
	 */
	v1 = pBt + 24
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_NO_WAL))
	if iVersion == int32(1) {
		v1 = pBt + 24
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(BTS_NO_WAL))
	}
	rc = _sqlite3BtreeBeginTrans(tls, pBtree, 0, uintptr(0))
	if rc == SQLITE_OK {
		aData = (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FaData
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + 18))) != libc.Int32FromUint8(libc.Uint8FromInt32(iVersion)) || libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + 19))) != libc.Int32FromUint8(libc.Uint8FromInt32(iVersion)) {
			rc = _sqlite3BtreeBeginTrans(tls, pBtree, int32(2), uintptr(0))
			if rc == SQLITE_OK {
				rc = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer((*TBtShared)(unsafe.Pointer(pBt)).FpPage1)).FpDbPage)
				if rc == SQLITE_OK {
					**(**Tu8)(__ccgo_up(aData + 18)) = libc.Uint8FromInt32(iVersion)
					**(**Tu8)(__ccgo_up(aData + 19)) = libc.Uint8FromInt32(iVersion)
				}
			}
		}
	}
	v1 = pBt + 24
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTS_NO_WAL))
	return rc
}

// C documentation
//
//	/*
//	** This function is used as part of copying the current row from cursor
//	** pSrc into cursor pDest. If the cursors are open on intkey tables, then
//	** parameter iKey is used as the rowid value when the record is copied
//	** into pDest. Otherwise, the record is copied verbatim.
//	**
//	** This function does not actually write the new value to cursor pDest.
//	** Instead, it creates and populates any required overflow pages and
//	** writes the data for the new cell into the BtShared.pTmpSpace buffer
//	** for the destination database. The size of the cell, in bytes, is left
//	** in BtShared.nPreformatSize. The caller completes the insertion by
//	** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
//	**
//	** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
//	*/
func _sqlite3BtreeTransferRow(tls *libc.TLS, pDest uintptr, pSrc uintptr, iKey Ti64) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aIn, aOut, pBt, pPageOut, pPgnoOut, pSrcPager, v1 uintptr
	var nCopy int32
	var nIn, nOut, nRem Tu32
	var ovflIn TPgno
	var v2 uint32
	var _ /* pNew at bp+12 */ uintptr
	var _ /* pPageIn at bp+4 */ uintptr
	var _ /* pgnoNew at bp+8 */ TPgno
	var _ /* rc at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _, _, _, _ = aIn, aOut, nCopy, nIn, nOut, nRem, ovflIn, pBt, pPageOut, pPgnoOut, pSrcPager, v1, v2
	pBt = (*TBtCursor)(unsafe.Pointer(pDest)).FpBt
	aOut = (*TBtShared)(unsafe.Pointer(pBt)).FpTmpSpace /* Bytes of data still to copy */
	_getCellInfo(tls, pSrc)
	if (*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload < uint32(0x80) {
		v1 = aOut
		aOut = aOut + 1
		**(**Tu8)(__ccgo_up(v1)) = uint8((*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload)
	} else {
		aOut = aOut + uintptr(_sqlite3PutVarint(tls, aOut, uint64((*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload)))
	}
	if (*TBtCursor)(unsafe.Pointer(pDest)).FpKeyInfo == uintptr(0) {
		aOut = aOut + uintptr(_sqlite3PutVarint(tls, aOut, libc.Uint64FromInt64(iKey)))
	}
	nIn = uint32((*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnLocal)
	aIn = (*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FpPayload
	if aIn+uintptr(nIn) > (*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pSrc)).FpPage)).FaDataEnd {
		return _sqlite3CorruptError(tls, int32(82970))
	}
	nRem = (*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload
	if nIn == nRem && nIn < uint32((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pDest)).FpPage)).FmaxLocal) {
		libc.Xmemcpy(tls, aOut, aIn, nIn)
		(*TBtShared)(unsafe.Pointer(pBt)).FnPreformatSize = libc.Int32FromUint32(nIn + libc.Uint32FromInt32(int32(aOut)-int32((*TBtShared)(unsafe.Pointer(pBt)).FpTmpSpace)))
		return SQLITE_OK
	} else {
		**(**int32)(__ccgo_up(bp)) = SQLITE_OK
		pSrcPager = (*TBtShared)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pSrc)).FpBt)).FpPager
		pPgnoOut = uintptr(0)
		ovflIn = uint32(0)
		**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
		pPageOut = uintptr(0) /* Size of output buffer aOut[] */
		nOut = libc.Uint32FromInt32(_btreePayloadToLocal(tls, (*TBtCursor)(unsafe.Pointer(pDest)).FpPage, libc.Int64FromUint32((*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload)))
		(*TBtShared)(unsafe.Pointer(pBt)).FnPreformatSize = libc.Int32FromUint32(nOut) + (int32(aOut) - int32((*TBtShared)(unsafe.Pointer(pBt)).FpTmpSpace))
		if nOut < (*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FnPayload {
			pPgnoOut = aOut + uintptr(nOut)
			**(**int32)(__ccgo_up(pBt + 88)) += int32(4)
		}
		if nRem > nIn {
			if aIn+uintptr(nIn)+uintptr(4) > (*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pSrc)).FpPage)).FaDataEnd {
				return _sqlite3CorruptError(tls, int32(82995))
			}
			ovflIn = _sqlite3Get4byte(tls, (*TBtCursor)(unsafe.Pointer(pSrc)).Finfo.FpPayload+uintptr(nIn))
		}
		for cond := true; cond; cond = nRem > uint32(0) && **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			nRem = nRem - nOut
			for cond := true; cond; cond = **(**int32)(__ccgo_up(bp)) == SQLITE_OK && nOut > uint32(0) {
				if nIn > uint32(0) {
					if nOut < nIn {
						v2 = nOut
					} else {
						v2 = nIn
					}
					nCopy = libc.Int32FromUint32(v2)
					libc.Xmemcpy(tls, aOut, aIn, libc.Uint32FromInt32(nCopy))
					nOut = nOut - libc.Uint32FromInt32(nCopy)
					nIn = nIn - libc.Uint32FromInt32(nCopy)
					aOut = aOut + uintptr(nCopy)
					aIn = aIn + uintptr(nCopy)
				}
				if nOut > uint32(0) {
					_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 4)))
					**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
					**(**int32)(__ccgo_up(bp)) = _sqlite3PagerGet(tls, pSrcPager, ovflIn, bp+4, int32(PAGER_GET_READONLY))
					if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
						aIn = _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp + 4)))
						ovflIn = _sqlite3Get4byte(tls, aIn)
						aIn = aIn + uintptr(4)
						nIn = (*TBtShared)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pSrc)).FpBt)).FusableSize - uint32(4)
					}
				}
			}
			if **(**int32)(__ccgo_up(bp)) == SQLITE_OK && nRem > uint32(0) && pPgnoOut != 0 {
				**(**TPgno)(__ccgo_up(bp + 8)) = uint32(0) /* Prevent harmless static-analyzer warning */
				**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
				**(**int32)(__ccgo_up(bp)) = _allocateBtreePage(tls, pBt, bp+12, bp+8, uint32(0), uint8(0))
				_sqlite3Put4byte(tls, pPgnoOut, **(**TPgno)(__ccgo_up(bp + 8)))
				if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 && pPageOut != 0 {
					_ptrmapPut(tls, pBt, **(**TPgno)(__ccgo_up(bp + 8)), uint8(PTRMAP_OVERFLOW2), (*TMemPage)(unsafe.Pointer(pPageOut)).Fpgno, bp)
				}
				_releasePage(tls, pPageOut)
				pPageOut = **(**uintptr)(__ccgo_up(bp + 12))
				if pPageOut != 0 {
					pPgnoOut = (*TMemPage)(unsafe.Pointer(pPageOut)).FaData
					_sqlite3Put4byte(tls, pPgnoOut, uint32(0))
					aOut = pPgnoOut + 4
					if (*TBtShared)(unsafe.Pointer(pBt)).FusableSize-uint32(4) < nRem {
						v2 = (*TBtShared)(unsafe.Pointer(pBt)).FusableSize - uint32(4)
					} else {
						v2 = nRem
					}
					nOut = v2
				}
			}
		}
		_releasePage(tls, pPageOut)
		_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 4)))
		return **(**int32)(__ccgo_up(bp))
	}
	return r
}

// C documentation
//
//	/*
//	** Generate code that will increment the schema cookie.
//	**
//	** The schema cookie is used to determine when the schema for the
//	** database changes.  After each schema change, the cookie value
//	** changes.  When a process first reads the schema it records the
//	** cookie.  Thereafter, whenever it goes to access the database,
//	** it checks the cookie to make sure the schema has not changed
//	** since it was last read.
//	**
//	** This plan is not completely bullet-proof.  It is possible for
//	** the schema to change multiple times and for the cookie to be
//	** set back to prior value.  But schema changes are infrequent
//	** and the probability of hitting the same cookie value is only
//	** 1 chance in 2^32.  So we're safe enough.
//	**
//	** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
//	** the schema-version whenever the schema changes.
//	*/
func _sqlite3ChangeCookie(tls *libc.TLS, pParse uintptr, iDb int32) {
	var db, v uintptr
	_, _ = db, v
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	_sqlite3VdbeAddOp3(tls, v, int32(OP_SetCookie), iDb, int32(BTREE_SCHEMA_VERSION), libc.Int32FromUint32(libc.Uint32FromInt32(1)+libc.Uint32FromInt32((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema)).Fschema_cookie)))
}

// C documentation
//
//	/*
//	** Generate code for the trigger program associated with trigger p on
//	** table pTab. The reg, orconf and ignoreJump parameters passed to this
//	** function are the same as those described in the header function for
//	** sqlite3CodeRowTrigger()
//	*/
func _sqlite3CodeRowTriggerDirect(tls *libc.TLS, pParse uintptr, p uintptr, pTab uintptr, reg int32, orconf int32, ignoreJump int32) {
	var bRecursive, v1 int32
	var pPrg, v, v2 uintptr
	_, _, _, _, _ = bRecursive, pPrg, v, v1, v2
	v = _sqlite3GetVdbe(tls, pParse)
	pPrg = _getRowTrigger(tls, pParse, p, pTab, orconf)
	/* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
	 ** is a pointer to the sub-vdbe containing the trigger program.  */
	if pPrg != 0 {
		bRecursive = libc.BoolInt32((*TTrigger)(unsafe.Pointer(p)).FzName != 0 && uint64(0) == (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Fflags&uint64(SQLITE_RecTriggers))
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		_sqlite3VdbeAddOp4(tls, v, int32(OP_Program), reg, ignoreJump, v1, (*TTriggerPrg)(unsafe.Pointer(pPrg)).FpProgram, -int32(4))
		/* Set the P5 operand of the OP_Program instruction to non-zero if
		 ** recursive invocation of this trigger program is disallowed. Recursive
		 ** invocation is disallowed if (a) the sub-program is really a trigger,
		 ** not a foreign key action, and (b) the flag to enable recursive triggers
		 ** is clear.  */
		_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(bRecursive))
	}
}

// C documentation
//
//	/*
//	** Return the expression associated with a column.  The expression might be
//	** the DEFAULT clause or the AS clause of a generated column.
//	** Return NULL if the column has no associated expression.
//	*/
func _sqlite3ColumnExpr(tls *libc.TLS, pTab uintptr, pCol uintptr) (r uintptr) {
	if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt) == 0 {
		return uintptr(0)
	}
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_NORM)) {
		return uintptr(0)
	}
	if (*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpDfltList == uintptr(0) {
		return uintptr(0)
	}
	if (*TExprList)(unsafe.Pointer((*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpDfltList)).FnExpr < libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt) {
		return uintptr(0)
	}
	return (*(*TExprList_item)(unsafe.Pointer((*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpDfltList + 8 + uintptr(libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt)-int32(1))*20))).FpExpr
}

// C documentation
//
//	/*
//	** Return the index of a column in a table.  Return -1 if the column
//	** is not contained in the table.
//	*/
func _sqlite3ColumnIndex(tls *libc.TLS, pTab uintptr, zCol uintptr) (r int32) {
	var aCol uintptr
	var h Tu8
	var i, nCol int32
	_, _, _, _ = aCol, h, i, nCol
	h = _sqlite3StrIHash(tls, zCol)
	aCol = (*TTable)(unsafe.Pointer(pTab)).FaCol
	nCol = int32((*TTable)(unsafe.Pointer(pTab)).FnCol)
	/* See if the aHx gives us a lucky match */
	i = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pTab + 64 + uintptr(uint32(h)%uint32(16)))))
	if libc.Int32FromUint8((**(**TColumn)(__ccgo_up(aCol + uintptr(i)*12))).FhName) == libc.Int32FromUint8(h) && _sqlite3StrICmp(tls, (**(**TColumn)(__ccgo_up(aCol + uintptr(i)*12))).FzCnName, zCol) == 0 {
		return i
	}
	/* No lucky match from the hash table.  Do a full search. */
	i = 0
	for int32(1) != 0 {
		if libc.Int32FromUint8((**(**TColumn)(__ccgo_up(aCol + uintptr(i)*12))).FhName) == libc.Int32FromUint8(h) && _sqlite3StrICmp(tls, (**(**TColumn)(__ccgo_up(aCol + uintptr(i)*12))).FzCnName, zCol) == 0 {
			return i
		}
		i = i + 1
		if i >= nCol {
			break
		}
	}
	return -int32(1)
}

// C documentation
//
//	/*
//	** Set the collating sequence name for a column.
//	*/
func _sqlite3ColumnSetColl(tls *libc.TLS, db uintptr, pCol uintptr, zColl uintptr) {
	var n, nColl Ti64
	var zNew, v1 uintptr
	_, _, _, _ = n, nColl, zNew, v1
	n = int64(_sqlite3Strlen30(tls, (*TColumn)(unsafe.Pointer(pCol)).FzCnName) + int32(1))
	if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FcolFlags)&int32(COLFLAG_HASTYPE) != 0 {
		n = n + int64(_sqlite3Strlen30(tls, (*TColumn)(unsafe.Pointer(pCol)).FzCnName+uintptr(n))+int32(1))
	}
	nColl = int64(_sqlite3Strlen30(tls, zColl) + int32(1))
	zNew = _sqlite3DbRealloc(tls, db, (*TColumn)(unsafe.Pointer(pCol)).FzCnName, libc.Uint64FromInt64(nColl+n))
	if zNew != 0 {
		(*TColumn)(unsafe.Pointer(pCol)).FzCnName = zNew
		libc.Xmemcpy(tls, (*TColumn)(unsafe.Pointer(pCol)).FzCnName+uintptr(n), zColl, libc.Uint32FromInt64(nColl))
		v1 = pCol + 10
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(COLFLAG_HASCOLL))
	}
}

// C documentation
//
//	/*
//	** Set the expression associated with a column.  This is usually
//	** the DEFAULT value, but might also be the expression that computes
//	** the value for a generated column.
//	*/
func _sqlite3ColumnSetExpr(tls *libc.TLS, pParse uintptr, pTab uintptr, pCol uintptr, pExpr uintptr) {
	var pList uintptr
	var v1 int32
	_, _ = pList, v1
	pList = (*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpDfltList
	if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt) == 0 || pList == uintptr(0) || (*TExprList)(unsafe.Pointer(pList)).FnExpr < libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt) {
		if pList == uintptr(0) {
			v1 = int32(1)
		} else {
			v1 = (*TExprList)(unsafe.Pointer(pList)).FnExpr + int32(1)
		}
		(*TColumn)(unsafe.Pointer(pCol)).FiDflt = libc.Uint16FromInt32(v1)
		(*(*struct {
			FaddColOffset int32
			FpFKey        uintptr
			FpDfltList    uintptr
		})(unsafe.Pointer(pTab + 44))).FpDfltList = _sqlite3ExprListAppend(tls, pParse, pList, pExpr)
	} else {
		_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt)-int32(1))*20))).FpExpr)
		(*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FiDflt)-int32(1))*20))).FpExpr = pExpr
	}
}

// C documentation
//
//	/*
//	** Return the declared type of a column.  Or return zDflt if the column
//	** has no declared type.
//	**
//	** The column type is an extra string stored after the zero-terminator on
//	** the column name if and only if the COLFLAG_HASTYPE flag is set.
//	*/
func _sqlite3ColumnType(tls *libc.TLS, pCol uintptr, zDflt uintptr) (r uintptr) {
	if libc.Int32FromUint16((*TColumn)(unsafe.Pointer(pCol)).FcolFlags)&int32(COLFLAG_HASTYPE) != 0 {
		return (*TColumn)(unsafe.Pointer(pCol)).FzCnName + uintptr(libc.Xstrlen(tls, (*TColumn)(unsafe.Pointer(pCol)).FzCnName)) + uintptr(1)
	} else {
		if int32(uint32(*(*uint8)(unsafe.Pointer(pCol + 4))&0xf0>>4)) != 0 {
			return _sqlite3StdType[int32(uint32(*(*uint8)(unsafe.Pointer(pCol + 4))&0xf0>>4))-int32(1)]
		} else {
			return zDflt
		}
	}
	return r
}

// C documentation
//
//	/*
//	** This routine is called when a commit occurs.
//	*/
func _sqlite3CommitInternalChanges(tls *libc.TLS, db uintptr) {
	**(**Tu32)(__ccgo_up(db + 24)) &= libc.Uint32FromInt32(^libc.Int32FromInt32(DBFLAG_SchemaChange))
}

func _sqlite3CompileOptions(tls *libc.TLS, pnOpt uintptr) (r uintptr) {
	**(**int32)(__ccgo_up(pnOpt)) = libc.Int32FromUint32(libc.Uint32FromInt64(224) / libc.Uint32FromInt64(4))
	return uintptr(unsafe.Pointer(&_sqlite3azCompileOpt))
}

/************** End of ctime.c ***********************************************/
/************** Begin file global.c ******************************************/
/*
** 2008 June 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains definitions of global variables and constants.
 */
/* #include "sqliteInt.h" */

// C documentation
//
//	/*
//	** This routine generates code to finish the INSERT or UPDATE operation
//	** that was started by a prior call to sqlite3GenerateConstraintChecks.
//	** A consecutive range of registers starting at regNewData contains the
//	** rowid and the content to be inserted.
//	**
//	** The arguments to this routine should be the same as the first six
//	** arguments to sqlite3GenerateConstraintChecks.
//	*/
func _sqlite3CompleteInsertion(tls *libc.TLS, pParse uintptr, pTab uintptr, iDataCur int32, iIdxCur int32, regNewData int32, aRegIdx uintptr, update_flags int32, appendBias int32, useSeekResult int32) {
	var i, v2 int32
	var pIdx, v uintptr
	var pik_flags Tu8
	_, _, _, _, _ = i, pIdx, pik_flags, v, v2 /* Loop counter */
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	/* This table is not a VIEW */
	i = 0
	pIdx = (*TTable)(unsafe.Pointer(pTab)).FpIndex
	for {
		if !(pIdx != 0) {
			break
		}
		/* All REPLACE indexes are at the end of the list */
		if **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)) == 0 {
			goto _1
		}
		if (*TIndex)(unsafe.Pointer(pIdx)).FpPartIdxWhere != 0 {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_IsNull), **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)), _sqlite3VdbeCurrentAddr(tls, v)+int32(2))
		}
		if useSeekResult != 0 {
			v2 = int32(OPFLAG_USESEEKRESULT)
		} else {
			v2 = 0
		}
		pik_flags = libc.Uint8FromInt32(v2)
		if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x3>>0)) == int32(SQLITE_IDXTYPE_PRIMARYKEY) && !((*TTable)(unsafe.Pointer(pTab)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) {
			pik_flags = libc.Uint8FromInt32(int32(pik_flags) | libc.Int32FromInt32(OPFLAG_NCHANGE))
			pik_flags = libc.Uint8FromInt32(int32(pik_flags) | update_flags&libc.Int32FromInt32(OPFLAG_SAVEPOSITION))
			if update_flags == 0 {
				_codeWithoutRowidPreupdate(tls, pParse, pTab, iIdxCur+i, **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)))
			}
		}
		if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x8>>3)) != 0 {
			v2 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
		} else {
			v2 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
		}
		_sqlite3VdbeAddOp4Int(tls, v, int32(OP_IdxInsert), iIdxCur+i, **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)), **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4))+int32(1), v2)
		_sqlite3VdbeChangeP5(tls, v, uint16(pik_flags))
		goto _1
	_1:
		;
		pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		i = i + 1
	}
	if !((*TTable)(unsafe.Pointer(pTab)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) {
		return
	}
	if (*TParse)(unsafe.Pointer(pParse)).Fnested != 0 {
		pik_flags = uint8(0)
	} else {
		pik_flags = uint8(OPFLAG_NCHANGE)
		if update_flags != 0 {
			v2 = update_flags
		} else {
			v2 = int32(OPFLAG_LASTROWID)
		}
		pik_flags = libc.Uint8FromInt32(int32(pik_flags) | v2)
	}
	if appendBias != 0 {
		pik_flags = libc.Uint8FromInt32(int32(pik_flags) | libc.Int32FromInt32(OPFLAG_APPEND))
	}
	if useSeekResult != 0 {
		pik_flags = libc.Uint8FromInt32(int32(pik_flags) | libc.Int32FromInt32(OPFLAG_USESEEKRESULT))
	}
	_sqlite3VdbeAddOp3(tls, v, int32(OP_Insert), iDataCur, **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)), regNewData)
	if !((*TParse)(unsafe.Pointer(pParse)).Fnested != 0) {
		_sqlite3VdbeAppendP4(tls, v, pTab, -int32(5))
	}
	_sqlite3VdbeChangeP5(tls, v, uint16(pik_flags))
}

// C documentation
//
//	/*
//	** If p2 exists and p1 and p2 have the same number of terms, then change
//	** every term of p1 to have the same sort order as p2 and return true.
//	**
//	** If p2 is NULL or p1 and p2 are different lengths, then make no changes
//	** and return false.
//	**
//	** p1 must be non-NULL.
//	*/
func _sqlite3CopySortOrder(tls *libc.TLS, p1 uintptr, p2 uintptr) (r int32) {
	var ii int32
	var sortFlags Tu8
	_, _ = ii, sortFlags
	if p2 != 0 && (*TExprList)(unsafe.Pointer(p1)).FnExpr == (*TExprList)(unsafe.Pointer(p2)).FnExpr {
		ii = 0
		for {
			if !(ii < (*TExprList)(unsafe.Pointer(p1)).FnExpr) {
				break
			}
			sortFlags = libc.Uint8FromInt32(libc.Int32FromUint8((*(*TExprList_item)(unsafe.Pointer(p2 + 8 + uintptr(ii)*20))).Ffg.FsortFlags) & int32(KEYINFO_ORDER_DESC))
			(*(*TExprList_item)(unsafe.Pointer(p1 + 8 + uintptr(ii)*20))).Ffg.FsortFlags = sortFlags
			goto _1
		_1:
			;
			ii = ii + 1
		}
		return int32(1)
	} else {
		return 0
	}
	return r
}

// C documentation
//
//	/*
//	** Allocate and return a pointer to an expression to load the column iCol
//	** from datasource iSrc in SrcList pSrc.
//	*/
func _sqlite3CreateColumnExpr(tls *libc.TLS, db uintptr, pSrc uintptr, iSrc int32, iCol int32) (r uintptr) {
	var p, pItem, pTab, v1 uintptr
	var v2 uint64
	var v3 int32
	_, _, _, _, _, _ = p, pItem, pTab, v1, v2, v3
	p = _sqlite3ExprAlloc(tls, db, int32(TK_COLUMN), uintptr(0), 0)
	if p != 0 {
		pItem = pSrc + 8 + uintptr(iSrc)*48
		v1 = (*TSrcItem)(unsafe.Pointer(pItem)).FpSTab
		(*TExpr)(unsafe.Pointer(p)).Fy.FpTab = v1
		pTab = v1
		(*TExpr)(unsafe.Pointer(p)).FiTable = (*TSrcItem)(unsafe.Pointer(pItem)).FiCursor
		if int32((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).Fy.FpTab)).FiPKey) == iCol {
			(*TExpr)(unsafe.Pointer(p)).FiColumn = int16(-int32(1))
		} else {
			(*TExpr)(unsafe.Pointer(p)).FiColumn = int16(iCol)
			if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_HasGenerated) != uint32(0) && libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(iCol)*12))).FcolFlags)&int32(COLFLAG_GENERATED) != 0 {
				if int32((*TTable)(unsafe.Pointer(pTab)).FnCol) >= int32(64) {
					v2 = libc.Uint64FromInt32(-libc.Int32FromInt32(1))
				} else {
					v2 = libc.Uint64FromInt32(1)<<(*TTable)(unsafe.Pointer(pTab)).FnCol - uint64(1)
				}
				(*TSrcItem)(unsafe.Pointer(pItem)).FcolUsed = v2
			} else {
				if iCol >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) {
					v3 = libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) - libc.Int32FromInt32(1)
				} else {
					v3 = iCol
				}
				**(**TBitmask)(__ccgo_up(pItem + 24)) |= libc.Uint64FromInt32(1) << v3
			}
		}
	}
	return p
}

func _sqlite3DbMallocSize(tls *libc.TLS, db uintptr, p uintptr) (r int32) {
	if db != 0 {
		if uint32(p) < uint32((*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpTrueEnd) {
			if uint32(p) >= uint32((*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpMiddle) {
				return int32(LOOKASIDE_SMALL)
			}
			if uint32(p) >= uint32((*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FpStart) {
				return libc.Int32FromUint16((*Tsqlite3)(unsafe.Pointer(db)).Flookaside.FszTrue)
			}
		}
	}
	return (*(*func(*libc.TLS, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fm.FxSize})))(tls, p)
}

// C documentation
//
//	/*
//	** Fill the Index.aiRowEst[] array with default information - information
//	** to be used when we have not run the ANALYZE command.
//	**
//	** aiRowEst[0] is supposed to contain the number of elements in the index.
//	** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
//	** number of rows in the table that match any particular value of the
//	** first column of the index.  aiRowEst[2] is an estimate of the number
//	** of rows that match any particular combination of the first 2 columns
//	** of the index.  And so forth.  It must always be the case that
//	*
//	**           aiRowEst[N]<=aiRowEst[N-1]
//	**           aiRowEst[N]>=1
//	**
//	** Apart from that, we have little to go on besides intuition as to
//	** how aiRowEst[] should be initialized.  The numbers generated here
//	** are based on typical values found in actual indices.
//	*/
func _sqlite3DefaultRowEst(tls *libc.TLS, pIdx uintptr) {
	var a uintptr
	var i, nCopy, v1 int32
	var x, v2 TLogEst
	_, _, _, _, _, _ = a, i, nCopy, x, v1, v2
	a = (*TIndex)(unsafe.Pointer(pIdx)).FaiRowLogEst
	if libc.Int32FromUint32(libc.Uint32FromInt64(10)/libc.Uint32FromInt64(2)) < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol) {
		v1 = libc.Int32FromUint32(libc.Uint32FromInt64(10) / libc.Uint32FromInt64(2))
	} else {
		v1 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
	}
	nCopy = v1
	/* Indexes with default row estimates should not have stat1 data */
	/* Set the first entry (number of rows in the index) to the estimated
	 ** number of rows in the table, or half the number of rows in the table
	 ** for a partial index.
	 **
	 ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
	 ** table but other parts we are having to guess at, then do not let the
	 ** estimated number of rows in the table be less than 1000 (LogEst 99).
	 ** Failure to do this can cause the indexes for which we do not have
	 ** stat1 data to be ignored by the query planner.
	 */
	x = (*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FnRowLogEst
	if int32(x) < int32(99) {
		v2 = libc.Int16FromInt32(99)
		x = v2
		(*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FnRowLogEst = v2
	}
	if (*TIndex)(unsafe.Pointer(pIdx)).FpPartIdxWhere != uintptr(0) {
		x = int16(int32(x) - libc.Int32FromInt32(10))
	}
	**(**TLogEst)(__ccgo_up(a)) = x
	/* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
	 ** 6 and each subsequent value (if any) is 5.  */
	libc.Xmemcpy(tls, a+1*2, uintptr(unsafe.Pointer(&_aVal)), libc.Uint32FromInt32(nCopy)*uint32(2))
	i = nCopy + int32(1)
	for {
		if !(i <= libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)) {
			break
		}
		**(**TLogEst)(__ccgo_up(a + uintptr(i)*2)) = int16(23)
		goto _3
	_3:
		;
		i = i + 1
	}
	if libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pIdx)).FonError) != OE_None {
		**(**TLogEst)(__ccgo_up(a + uintptr((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)*2)) = 0
	}
}

// C documentation
//
//	/*
//	** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
//	** clause is seen as part of a foreign key definition.  The isDeferred
//	** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
//	** The behavior of the most recently created foreign key is adjusted
//	** accordingly.
//	*/
func _sqlite3DeferForeignKey(tls *libc.TLS, pParse uintptr, isDeferred int32) {
	var pFKey, pTab, v1 uintptr
	_, _, _ = pFKey, pTab, v1
	v1 = (*TParse)(unsafe.Pointer(pParse)).FpNewTable
	pTab = v1
	if v1 == uintptr(0) {
		return
	}
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_NORM)) {
		return
	}
	v1 = (*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpFKey
	pFKey = v1
	if v1 == uintptr(0) {
		return
	}
	/* EV: R-30323-21917 */
	(*TFKey)(unsafe.Pointer(pFKey)).FisDeferred = libc.Uint8FromInt32(isDeferred)
}

// C documentation
//
//	/*
//	** Delete memory allocated for the column names of a table or view (the
//	** Table.aCol[] array).
//	*/
func _sqlite3DeleteColumnNames(tls *libc.TLS, db uintptr, pTable uintptr) {
	var i int32
	var pCol, v1 uintptr
	_, _, _ = i, pCol, v1
	v1 = (*TTable)(unsafe.Pointer(pTable)).FaCol
	pCol = v1
	if v1 != uintptr(0) {
		i = 0
		for {
			if !(i < int32((*TTable)(unsafe.Pointer(pTable)).FnCol)) {
				break
			}
			_sqlite3DbFree(tls, db, (*TColumn)(unsafe.Pointer(pCol)).FzCnName)
			goto _2
		_2:
			;
			i = i + 1
			pCol += 12
		}
		_sqlite3DbNNFreeNN(tls, db, (*TTable)(unsafe.Pointer(pTable)).FaCol)
		if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTable)).FeTabType) == TABTYP_NORM {
			_sqlite3ExprListDelete(tls, db, (*(*struct {
				FaddColOffset int32
				FpFKey        uintptr
				FpDfltList    uintptr
			})(unsafe.Pointer(pTable + 44))).FpDfltList)
		}
		if (*Tsqlite3)(unsafe.Pointer(db)).FpnBytesFreed == uintptr(0) {
			(*TTable)(unsafe.Pointer(pTable)).FaCol = uintptr(0)
			(*TTable)(unsafe.Pointer(pTable)).FnCol = 0
			if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTable)).FeTabType) == TABTYP_NORM {
				(*(*struct {
					FaddColOffset int32
					FpFKey        uintptr
					FpDfltList    uintptr
				})(unsafe.Pointer(pTable + 44))).FpDfltList = uintptr(0)
			}
		}
	}
}

// C documentation
//
//	/* The input list pList is the list of result set terms from a RETURNING
//	** clause.  The table that we are returning from is pTab.
//	**
//	** This routine makes a copy of the pList, and at the same time expands
//	** any "*" wildcards to be the complete set of columns from pTab.
//	*/
func _sqlite3ExpandReturning(tls *libc.TLS, pParse uintptr, pList uintptr, pTab uintptr) (r uintptr) {
	var db, pItem, pItem1, pNew, pNewExpr, pNewExpr1, pOldExpr uintptr
	var i, jj int32
	_, _, _, _, _, _, _, _, _ = db, i, jj, pItem, pItem1, pNew, pNewExpr, pNewExpr1, pOldExpr
	pNew = uintptr(0)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
			break
		}
		pOldExpr = (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FpExpr
		if pOldExpr == uintptr(0) {
			goto _1
		}
		if _isAsteriskTerm(tls, pParse, pOldExpr) != 0 {
			jj = 0
			for {
				if !(jj < int32((*TTable)(unsafe.Pointer(pTab)).FnCol)) {
					break
				}
				if libc.Int32FromUint16((*TColumn)(unsafe.Pointer((*TTable)(unsafe.Pointer(pTab)).FaCol+uintptr(jj)*12)).FcolFlags)&int32(COLFLAG_HIDDEN) != 0 {
					goto _2
				}
				pNewExpr = _sqlite3Expr(tls, db, int32(TK_ID), (**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(jj)*12))).FzCnName)
				pNew = _sqlite3ExprListAppend(tls, pParse, pNew, pNewExpr)
				if !((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0) {
					pItem = pNew + 8 + uintptr((*TExprList)(unsafe.Pointer(pNew)).FnExpr-int32(1))*20
					(*TExprList_item)(unsafe.Pointer(pItem)).FzEName = _sqlite3DbStrDup(tls, db, (**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(jj)*12))).FzCnName)
					libc.SetBitFieldPtr16Uint32(pItem+8+4, libc.Uint32FromInt32(ENAME_NAME), 0, 0x3)
				}
				goto _2
			_2:
				;
				jj = jj + 1
			}
		} else {
			pNewExpr1 = _sqlite3ExprDup(tls, db, pOldExpr, 0)
			pNew = _sqlite3ExprListAppend(tls, pParse, pNew, pNewExpr1)
			if !((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0) && (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FzEName != uintptr(0) {
				pItem1 = pNew + 8 + uintptr((*TExprList)(unsafe.Pointer(pNew)).FnExpr-int32(1))*20
				(*TExprList_item)(unsafe.Pointer(pItem1)).FzEName = _sqlite3DbStrDup(tls, db, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FzEName)
				libc.SetBitFieldPtr16Uint32(pItem1+8+4, libc.Uint32FromInt32(int32(uint32(*(*uint16)(unsafe.Pointer(pList + 8 + uintptr(i)*20 + 8 + 4))&0x3>>0))), 0, 0x3)
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return pNew
}

// C documentation
//
//	/*
//	** Return FALSE if there is no chance that the expression can be NULL.
//	**
//	** If the expression might be NULL or if the expression is too complex
//	** to tell return TRUE.
//	**
//	** This routine is used as an optimization, to skip OP_IsNull opcodes
//	** when we know that a value cannot be NULL.  Hence, a false positive
//	** (returning TRUE when in fact the expression can never be NULL) might
//	** be a small performance hit but is otherwise harmless.  On the other
//	** hand, a false negative (returning FALSE when the result could be NULL)
//	** will likely result in an incorrect answer.  So when in doubt, return
//	** TRUE.
//	*/
func _sqlite3ExprCanBeNull(tls *libc.TLS, p uintptr) (r int32) {
	var op Tu8
	_ = op
	for libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_UPLUS) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_UMINUS) {
		p = (*TExpr)(unsafe.Pointer(p)).FpLeft
	}
	op = (*TExpr)(unsafe.Pointer(p)).Fop
	if libc.Int32FromUint8(op) == int32(TK_REGISTER) {
		op = (*TExpr)(unsafe.Pointer(p)).Fop2
	}
	switch libc.Int32FromUint8(op) {
	case int32(TK_INTEGER):
		fallthrough
	case int32(TK_STRING):
		fallthrough
	case int32(TK_FLOAT):
		fallthrough
	case int32(TK_BLOB):
		return 0
	case int32(TK_COLUMN):
		return libc.BoolInt32((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_CanBeNull)) != uint32(0) || (*TExpr)(unsafe.Pointer(p)).Fy.FpTab == uintptr(0) || int32((*TExpr)(unsafe.Pointer(p)).FiColumn) >= 0 && (*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).Fy.FpTab)).FaCol != uintptr(0) && int32((*TExpr)(unsafe.Pointer(p)).FiColumn) < int32((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).Fy.FpTab)).FnCol) && int32(uint32(*(*uint8)(unsafe.Pointer((*TTable)(unsafe.Pointer((*TExpr)(unsafe.Pointer(p)).Fy.FpTab)).FaCol + uintptr((*TExpr)(unsafe.Pointer(p)).FiColumn)*12 + 4))&0xf>>0)) == 0)
	default:
		return int32(1)
	}
	return r
}

// C documentation
//
//	/*
//	** Return TRUE if expression pExpr is able to return a subtype.
//	**
//	** A TRUE return does not guarantee that a subtype will be returned.
//	** It only indicates that a subtype return is possible.  False positives
//	** are acceptable as they only disable an optimization.  False negatives,
//	** on the other hand, can lead to incorrect answers.
//	*/
func _sqlite3ExprCanReturnSubtype(tls *libc.TLS, pParse uintptr, pExpr uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	libc.Xmemset(tls, bp, 0, uint32(28))
	(**(**TWalker)(__ccgo_up(bp))).FpParse = pParse
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_exprNodeCanReturnSubtype)
	_sqlite3WalkExpr(tls, bp, pExpr)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

// C documentation
//
//	/*
//	** Generate code that pushes the value of every element of the given
//	** expression list into a sequence of registers beginning at target.
//	**
//	** Return the number of elements evaluated.  The number returned will
//	** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
//	** is defined.
//	**
//	** The SQLITE_ECEL_DUP flag prevents the arguments from being
//	** filled using OP_SCopy.  OP_Copy must be used instead.
//	**
//	** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
//	** factored out into initialization code.
//	**
//	** The SQLITE_ECEL_REF flag means that expressions in the list with
//	** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
//	** in registers at srcReg, and so the value can be copied from there.
//	** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
//	** are simply omitted rather than being copied from srcReg.
//	*/
func _sqlite3ExprCodeExprList(tls *libc.TLS, pParse uintptr, pList uintptr, target int32, srcReg int32, flags Tu8) (r int32) {
	var copyOp Tu8
	var i, inReg, j, n, v1 int32
	var pExpr, pItem, pOp, v, v5 uintptr
	var v4 bool
	_, _, _, _, _, _, _, _, _, _, _, _ = copyOp, i, inReg, j, n, pExpr, pItem, pOp, v, v1, v4, v5
	if libc.Int32FromUint8(flags)&int32(SQLITE_ECEL_DUP) != 0 {
		v1 = int32(OP_Copy)
	} else {
		v1 = int32(OP_SCopy)
	}
	copyOp = libc.Uint8FromInt32(v1)
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	/* Never gets this far otherwise */
	n = (*TExprList)(unsafe.Pointer(pList)).FnExpr
	if !(int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x80>>7)) != 0) {
		flags = libc.Uint8FromInt32(int32(flags) & ^libc.Int32FromInt32(SQLITE_ECEL_FACTOR))
	}
	pItem = pList + 8
	i = libc.Int32FromInt32(0)
	for {
		if !(i < n) {
			break
		}
		pExpr = (*TExprList_item)(unsafe.Pointer(pItem)).FpExpr
		if v4 = libc.Int32FromUint8(flags)&int32(SQLITE_ECEL_REF) != 0; v4 {
			v1 = libc.Int32FromUint16((*(*struct {
				FiOrderByCol Tu16
				FiAlias      Tu16
			})(unsafe.Pointer(pItem + 16))).FiOrderByCol)
			j = v1
		}
		if v4 && v1 > 0 {
			if libc.Int32FromUint8(flags)&int32(SQLITE_ECEL_OMITREF) != 0 {
				i = i - 1
				n = n - 1
			} else {
				_sqlite3VdbeAddOp2(tls, v, libc.Int32FromUint8(copyOp), j+srcReg-int32(1), target+i)
			}
		} else {
			if libc.Int32FromUint8(flags)&int32(SQLITE_ECEL_FACTOR) != 0 && _sqlite3ExprIsConstantNotJoin(tls, pParse, pExpr) != 0 {
				_sqlite3ExprCodeRunJustOnce(tls, pParse, pExpr, target+i)
			} else {
				inReg = _sqlite3ExprCodeTarget(tls, pParse, pExpr, target+i)
				if inReg != target+i {
					if v4 = libc.Int32FromUint8(copyOp) == int32(OP_Copy); v4 {
						v5 = _sqlite3VdbeGetLastOp(tls, v)
						pOp = v5
					}
					if v4 && libc.Int32FromUint8((*TVdbeOp)(unsafe.Pointer(v5)).Fopcode) == int32(OP_Copy) && (*TVdbeOp)(unsafe.Pointer(pOp)).Fp1+(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3+int32(1) == inReg && (*TVdbeOp)(unsafe.Pointer(pOp)).Fp2+(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3+int32(1) == target+i && libc.Int32FromUint16((*TVdbeOp)(unsafe.Pointer(pOp)).Fp5) == 0 {
						(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3 = (*TVdbeOp)(unsafe.Pointer(pOp)).Fp3 + 1
					} else {
						_sqlite3VdbeAddOp2(tls, v, libc.Int32FromUint8(copyOp), inReg, target+i)
					}
				}
			}
		}
		goto _2
	_2:
		;
		i = i + 1
		pItem += 20
	}
	return n
}

// C documentation
//
//	/*
//	** Generate code that will evaluate expression pExpr just one time
//	** per prepared statement execution.
//	**
//	** If the expression uses functions (that might throw an exception) then
//	** guard them with an OP_Once opcode to ensure that the code is only executed
//	** once. If no functions are involved, then factor the code out and put it at
//	** the end of the prepared statement in the initialization section.
//	**
//	** If regDest>0 then the result is always stored in that register and the
//	** result is not reusable.  If regDest<0 then this routine is free to
//	** store the value wherever it wants.  The register where the expression
//	** is stored is returned.  When regDest<0, two identical expressions might
//	** code to the same register, if they do not contain function calls and hence
//	** are factored out into the initialization section at the end of the
//	** prepared statement.
//	*/
func _sqlite3ExprCodeRunJustOnce(tls *libc.TLS, pParse uintptr, pExpr uintptr, regDest int32) (r int32) {
	var addr, i, v2 int32
	var p, pItem, pItem1, v, v3 uintptr
	_, _, _, _, _, _, _, _ = addr, i, p, pItem, pItem1, v, v2, v3
	p = (*TParse)(unsafe.Pointer(pParse)).FpConstExpr
	if regDest < 0 && p != 0 {
		pItem = p + 8
		i = (*TExprList)(unsafe.Pointer(p)).FnExpr
		for {
			if !(i > 0) {
				break
			}
			if int32(uint32(*(*uint16)(unsafe.Pointer(pItem + 8 + 4))&0x8>>3)) != 0 && _sqlite3ExprCompare(tls, uintptr(0), (*TExprList_item)(unsafe.Pointer(pItem)).FpExpr, pExpr, -int32(1)) == 0 {
				return *(*int32)(unsafe.Pointer(pItem + 16))
			}
			goto _1
		_1:
			;
			pItem += 20
			i = i - 1
		}
	}
	pExpr = _sqlite3ExprDup(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pExpr, 0)
	if pExpr != uintptr(0) && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_HasFunc)) != uint32(0) {
		v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
		addr = _sqlite3VdbeAddOp0(tls, v, int32(OP_Once))
		libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(0), 7, 0x80)
		if !((*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0) {
			if regDest < 0 {
				v3 = pParse + 48
				*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
				v2 = *(*int32)(unsafe.Pointer(v3))
				regDest = v2
			}
			_sqlite3ExprCode(tls, pParse, pExpr, regDest)
		}
		libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(1), 7, 0x80)
		_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pExpr)
		_sqlite3VdbeJumpHere(tls, v, addr)
	} else {
		p = _sqlite3ExprListAppend(tls, pParse, p, pExpr)
		if p != 0 {
			pItem1 = p + 8 + uintptr((*TExprList)(unsafe.Pointer(p)).FnExpr-int32(1))*20
			libc.SetBitFieldPtr16Uint32(pItem1+8+4, libc.BoolUint32(regDest < libc.Int32FromInt32(0)), 3, 0x8)
			if regDest < 0 {
				v3 = pParse + 48
				*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
				v2 = *(*int32)(unsafe.Pointer(v3))
				regDest = v2
			}
			*(*int32)(unsafe.Pointer(pItem1 + 16)) = regDest
		}
		(*TParse)(unsafe.Pointer(pParse)).FpConstExpr = p
	}
	return regDest
}

// C documentation
//
//	/*
//	** Generate code to evaluate an expression and store the results
//	** into a register.  Return the register number where the results
//	** are stored.
//	**
//	** If the register is a temporary register that can be deallocated,
//	** then write its number into *pReg.  If the result register is not
//	** a temporary, then set *pReg to zero.
//	**
//	** If pExpr is a constant, then this routine might generate this
//	** code to fill the register in the initialization section of the
//	** VDBE program, in order to factor it out of the evaluation loop.
//	*/
func _sqlite3ExprCodeTemp(tls *libc.TLS, pParse uintptr, pExpr uintptr, pReg uintptr) (r int32) {
	var r1, r2 int32
	_, _ = r1, r2
	pExpr = _sqlite3ExprSkipCollateAndLikely(tls, pExpr)
	if int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x80>>7)) != 0 && pExpr != uintptr(0) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_REGISTER) && _sqlite3ExprIsConstantNotJoin(tls, pParse, pExpr) != 0 {
		**(**int32)(__ccgo_up(pReg)) = 0
		r2 = _sqlite3ExprCodeRunJustOnce(tls, pParse, pExpr, -int32(1))
	} else {
		r1 = _sqlite3GetTempReg(tls, pParse)
		r2 = _sqlite3ExprCodeTarget(tls, pParse, pExpr, r1)
		if r2 == r1 {
			**(**int32)(__ccgo_up(pReg)) = r1
		} else {
			_sqlite3ReleaseTempReg(tls, pParse, r1)
			**(**int32)(__ccgo_up(pReg)) = 0
		}
	}
	return r2
}

// C documentation
//
//	/*
//	** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
//	** return the appropriate colUsed mask.
//	*/
func _sqlite3ExprColUsed(tls *libc.TLS, pExpr uintptr) (r TBitmask) {
	var n int32
	var pExTab uintptr
	var v1 uint64
	_, _, _ = n, pExTab, v1
	n = int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)
	pExTab = (*TExpr)(unsafe.Pointer(pExpr)).Fy.FpTab
	if (*TTable)(unsafe.Pointer(pExTab)).FtabFlags&uint32(TF_HasGenerated) != uint32(0) && libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pExTab)).FaCol + uintptr(n)*12))).FcolFlags)&int32(COLFLAG_GENERATED) != 0 {
		if int32((*TTable)(unsafe.Pointer(pExTab)).FnCol) >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) {
			v1 = libc.Uint64FromInt32(-libc.Int32FromInt32(1))
		} else {
			v1 = libc.Uint64FromInt32(1)<<(*TTable)(unsafe.Pointer(pExTab)).FnCol - uint64(1)
		}
		return v1
	} else {
		if n >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) {
			n = libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) - libc.Int32FromInt32(1)
		}
		return libc.Uint64FromInt32(1) << n
	}
	return r
}

// C documentation
//
//	/*
//	** Do a deep comparison of two expression trees.  Return 0 if the two
//	** expressions are completely identical.  Return 1 if they differ only
//	** by a COLLATE operator at the top level.  Return 2 if there are differences
//	** other than the top-level COLLATE operator.
//	**
//	** If any subelement of pB has Expr.iTable==(-1) then it is allowed
//	** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
//	**
//	** The pA side might be using TK_REGISTER.  If that is the case and pB is
//	** not using TK_REGISTER but is otherwise equivalent, then still return 0.
//	**
//	** Sometimes this routine will return 2 even if the two expressions
//	** really are equivalent.  If we cannot prove that the expressions are
//	** identical, we return 2 just to be safe.  So if this routine
//	** returns 2, then you do not really know for certain if the two
//	** expressions are the same.  But if you get a 0 or 1 return, then you
//	** can be sure the expressions are the same.  In the places where
//	** this routine is used, it does not hurt to get an extra 2 - that
//	** just might result in some slightly slower code.  But returning
//	** an incorrect 0 or 1 could lead to a malfunction.
//	**
//	** If pParse is not NULL and SQLITE_EnableQPSG is off then TK_VARIABLE
//	** terms in pA with bindings in pParse->pReprepare can be matched against
//	** literals in pB.  The pParse->pVdbe->expmask bitmask is updated for
//	** each variable referenced.
//	*/
func _sqlite3ExprCompare(tls *libc.TLS, pParse uintptr, pA uintptr, pB uintptr, iTab int32) (r int32) {
	var combinedFlags Tu32
	var v1 int32
	_, _ = combinedFlags, v1
	if pA == uintptr(0) || pB == uintptr(0) {
		if pB == pA {
			v1 = 0
		} else {
			v1 = int32(2)
		}
		return v1
	}
	if pParse != 0 && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_VARIABLE) {
		return _exprCompareVariable(tls, pParse, pA, pB)
	}
	combinedFlags = (*TExpr)(unsafe.Pointer(pA)).Fflags | (*TExpr)(unsafe.Pointer(pB)).Fflags
	if combinedFlags&uint32(EP_IntValue) != 0 {
		if (*TExpr)(unsafe.Pointer(pA)).Fflags&(*TExpr)(unsafe.Pointer(pB)).Fflags&uint32(EP_IntValue) != uint32(0) && *(*int32)(unsafe.Pointer(pA + 8)) == *(*int32)(unsafe.Pointer(pB + 8)) {
			return 0
		}
		return int32(2)
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pB)).Fop) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_RAISE) {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_COLLATE) && _sqlite3ExprCompare(tls, pParse, (*TExpr)(unsafe.Pointer(pA)).FpLeft, pB, iTab) < int32(2) {
			return int32(1)
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pB)).Fop) == int32(TK_COLLATE) && _sqlite3ExprCompare(tls, pParse, pA, (*TExpr)(unsafe.Pointer(pB)).FpLeft, iTab) < int32(2) {
			return int32(1)
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_AGG_COLUMN) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pB)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(pB)).FiTable < 0 && (*TExpr)(unsafe.Pointer(pA)).FiTable == iTab {
			/* fall through */
		} else {
			return int32(2)
		}
	}
	if *(*uintptr)(unsafe.Pointer(pA + 8)) != 0 {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_FUNCTION) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_AGG_FUNCTION) {
			if _sqlite3StrICmp(tls, *(*uintptr)(unsafe.Pointer(pA + 8)), *(*uintptr)(unsafe.Pointer(pB + 8))) != 0 {
				return int32(2)
			}
			if libc.BoolInt32((*TExpr)(unsafe.Pointer(pA)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0)) != libc.BoolInt32((*TExpr)(unsafe.Pointer(pB)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0)) {
				return int32(2)
			}
			if (*TExpr)(unsafe.Pointer(pA)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
				if _sqlite3WindowCompare(tls, pParse, *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pA)).Fy)), *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pB)).Fy)), int32(1)) != 0 {
					return int32(2)
				}
			}
		} else {
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_NULL) {
				return 0
			} else {
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_COLLATE) {
					if Xsqlite3_stricmp(tls, *(*uintptr)(unsafe.Pointer(pA + 8)), *(*uintptr)(unsafe.Pointer(pB + 8))) != 0 {
						return int32(2)
					}
				} else {
					if *(*uintptr)(unsafe.Pointer(pB + 8)) != uintptr(0) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != int32(TK_COLUMN) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != int32(TK_AGG_COLUMN) && libc.Xstrcmp(tls, *(*uintptr)(unsafe.Pointer(pA + 8)), *(*uintptr)(unsafe.Pointer(pB + 8))) != 0 {
						return int32(2)
					}
				}
			}
		}
	}
	if (*TExpr)(unsafe.Pointer(pA)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Distinct)|libc.Int32FromInt32(EP_Commuted)) != (*TExpr)(unsafe.Pointer(pB)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Distinct)|libc.Int32FromInt32(EP_Commuted)) {
		return int32(2)
	}
	if combinedFlags&uint32(EP_TokenOnly) == uint32(0) {
		if combinedFlags&uint32(EP_xIsSelect) != 0 {
			return int32(2)
		}
		if combinedFlags&uint32(EP_FixedCol) == uint32(0) && _sqlite3ExprCompare(tls, pParse, (*TExpr)(unsafe.Pointer(pA)).FpLeft, (*TExpr)(unsafe.Pointer(pB)).FpLeft, iTab) != 0 {
			return int32(2)
		}
		if _sqlite3ExprCompare(tls, pParse, (*TExpr)(unsafe.Pointer(pA)).FpRight, (*TExpr)(unsafe.Pointer(pB)).FpRight, iTab) != 0 {
			return int32(2)
		}
		if _sqlite3ExprListCompare(tls, *(*uintptr)(unsafe.Pointer(pA + 20)), *(*uintptr)(unsafe.Pointer(pB + 20)), iTab) != 0 {
			return int32(2)
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != int32(TK_STRING) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != int32(TK_TRUEFALSE) && combinedFlags&uint32(EP_Reduced) == uint32(0) {
			if int32((*TExpr)(unsafe.Pointer(pA)).FiColumn) != int32((*TExpr)(unsafe.Pointer(pB)).FiColumn) {
				return int32(2)
			}
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop2) != libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pB)).Fop2) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) == int32(TK_TRUTH) {
				return int32(2)
			}
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pA)).Fop) != int32(TK_IN) && (*TExpr)(unsafe.Pointer(pA)).FiTable != (*TExpr)(unsafe.Pointer(pB)).FiTable && (*TExpr)(unsafe.Pointer(pA)).FiTable != iTab {
				return int32(2)
			}
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** Recursively delete an expression tree.
//	*/
func _sqlite3ExprDeleteNN(tls *libc.TLS, db uintptr, p uintptr) {
	var pLeft uintptr
	_ = pLeft
	goto exprDeleteRestart
exprDeleteRestart:
	;
	if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)|libc.Int32FromInt32(EP_Leaf)) != libc.Uint32FromInt32(0)) {
		/* The Expr.x union is never used at the same time as Expr.pRight */
		if (*TExpr)(unsafe.Pointer(p)).FpRight != 0 {
			_sqlite3ExprDeleteNN(tls, db, (*TExpr)(unsafe.Pointer(p)).FpRight)
		} else {
			if (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
				_sqlite3SelectDelete(tls, db, *(*uintptr)(unsafe.Pointer(p + 20)))
			} else {
				_sqlite3ExprListDelete(tls, db, *(*uintptr)(unsafe.Pointer(p + 20)))
				if (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
					_sqlite3WindowDelete(tls, db, *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(p)).Fy)))
				}
			}
		}
		if (*TExpr)(unsafe.Pointer(p)).FpLeft != 0 && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) != int32(TK_SELECT_COLUMN) {
			pLeft = (*TExpr)(unsafe.Pointer(p)).FpLeft
			if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Static)) != libc.Uint32FromInt32(0)) && !((*TExpr)(unsafe.Pointer(pLeft)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Static)) != libc.Uint32FromInt32(0)) {
				/* Avoid unnecessary recursion on unary operators */
				_sqlite3DbNNFreeNN(tls, db, p)
				p = pLeft
				goto exprDeleteRestart
			} else {
				_sqlite3ExprDeleteNN(tls, db, pLeft)
			}
		}
	}
	if !((*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Static)) != libc.Uint32FromInt32(0)) {
		_sqlite3DbNNFreeNN(tls, db, p)
	}
}

// C documentation
//
//	/*
//	** Compute and return a new Expr object which when passed to
//	** sqlite3ExprCode() will generate all necessary code to compute
//	** the iField-th column of the vector expression pVector.
//	**
//	** It is ok for pVector to be a scalar (as long as iField==0).
//	** In that case, this routine works like sqlite3ExprDup().
//	**
//	** The caller owns the returned Expr object and is responsible for
//	** ensuring that the returned value eventually gets freed.
//	**
//	** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
//	** then the returned object will reference pVector and so pVector must remain
//	** valid for the life of the returned object.  If pVector is a TK_VECTOR
//	** or a scalar expression, then it can be deleted as soon as this routine
//	** returns.
//	**
//	** A trick to cause a TK_SELECT pVector to be deleted together with
//	** the returned Expr object is to attach the pVector to the pRight field
//	** of the returned TK_SELECT_COLUMN Expr object.
//	*/
func _sqlite3ExprForVectorField(tls *libc.TLS, pParse uintptr, pVector uintptr, iField int32, nField int32) (r uintptr) {
	var pRet, ppVector uintptr
	_, _ = pRet, ppVector
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pVector)).Fop) == int32(TK_SELECT) {
		/* The TK_SELECT_COLUMN Expr node:
		 **
		 ** pLeft:           pVector containing TK_SELECT.  Not deleted.
		 ** pRight:          not used.  But recursively deleted.
		 ** iColumn:         Index of a column in pVector
		 ** iTable:          0 or the number of columns on the LHS of an assignment
		 ** pLeft->iTable:   First in an array of register holding result, or 0
		 **                  if the result is not yet computed.
		 **
		 ** sqlite3ExprDelete() specifically skips the recursive delete of
		 ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
		 ** can be attached to pRight to cause this node to take ownership of
		 ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
		 ** with the same pLeft pointer to the pVector, but only one of them
		 ** will own the pVector.
		 */
		pRet = _sqlite3PExpr(tls, pParse, int32(TK_SELECT_COLUMN), uintptr(0), uintptr(0))
		if pRet != 0 {
			**(**Tu32)(__ccgo_up(pRet + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_FullSize))
			(*TExpr)(unsafe.Pointer(pRet)).FiTable = nField
			(*TExpr)(unsafe.Pointer(pRet)).FiColumn = int16(iField)
			(*TExpr)(unsafe.Pointer(pRet)).FpLeft = pVector
		}
	} else {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pVector)).Fop) == int32(TK_VECTOR) {
			ppVector = *(*uintptr)(unsafe.Pointer(pVector + 20)) + 8 + uintptr(iField)*20
			pVector = **(**uintptr)(__ccgo_up(ppVector))
			if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) >= int32(PARSE_MODE_RENAME) {
				/* This must be a vector UPDATE inside a trigger */
				**(**uintptr)(__ccgo_up(ppVector)) = uintptr(0)
				return pVector
			}
		}
		pRet = _sqlite3ExprDup(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pVector, 0)
	}
	return pRet
}

// C documentation
//
//	/*
//	** Return true if we can prove the pE2 will always be true if pE1 is
//	** true.  Return false if we cannot complete the proof or if pE2 might
//	** be false.  Examples:
//	**
//	**     pE1: x==5        pE2: x==5             Result: true
//	**     pE1: x>0         pE2: x==5             Result: false
//	**     pE1: x=21        pE2: x=21 OR y=43     Result: true
//	**     pE1: x!=123      pE2: x IS NOT NULL    Result: true
//	**     pE1: x!=?1       pE2: x IS NOT NULL    Result: true
//	**     pE1: x IS NULL   pE2: x IS NOT NULL    Result: false
//	**     pE1: x IS ?2     pE2: x IS NOT NULL    Result: false
//	**     pE1: iif(x,y)    pE2: x                Result: true
//	**     PE1: iif(x,y,0)  pE2: x                Result: true
//	**
//	** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
//	** Expr.iTable<0 then assume a table number given by iTab.
//	**
//	** If pParse is not NULL, then the values of bound variables in pE1 are
//	** compared against literal values in pE2 and pParse->pVdbe->expmask is
//	** modified to record which bound variables are referenced.  If pParse
//	** is NULL, then false will be returned if pE1 contains any bound variables.
//	**
//	** When in doubt, return false.  Returning true might give a performance
//	** improvement.  Returning false might cause a performance reduction, but
//	** it will always give the correct answer and is hence always safe.
//	*/
func _sqlite3ExprImpliesExpr(tls *libc.TLS, pParse uintptr, pE1 uintptr, pE2 uintptr, iTab int32) (r int32) {
	if _sqlite3ExprCompare(tls, pParse, pE1, pE2, iTab) == 0 {
		return int32(1)
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pE2)).Fop) == int32(TK_OR) && (_sqlite3ExprImpliesExpr(tls, pParse, pE1, (*TExpr)(unsafe.Pointer(pE2)).FpLeft, iTab) != 0 || _sqlite3ExprImpliesExpr(tls, pParse, pE1, (*TExpr)(unsafe.Pointer(pE2)).FpRight, iTab) != 0) {
		return int32(1)
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pE2)).Fop) == int32(TK_NOTNULL) && _exprImpliesNotNull(tls, pParse, pE1, (*TExpr)(unsafe.Pointer(pE2)).FpLeft, iTab, 0) != 0 {
		return int32(1)
	}
	if _sqlite3ExprIsIIF(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pE1) != 0 {
		return _sqlite3ExprImpliesExpr(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pE1 + 20)) + 8))).FpExpr, pE2, iTab)
	}
	return 0
}

// C documentation
//
//	/*
//	** Return true (non-zero) if expression p can only be true if at least
//	** one column of table iTab is non-null.  In other words, return true
//	** if expression p will always be NULL or false if every column of iTab
//	** is NULL.
//	**
//	** False negatives are acceptable.  In other words, it is ok to return
//	** zero even if expression p will never be true of every column of iTab
//	** is NULL.  A false negative is merely a missed optimization opportunity.
//	**
//	** False positives are not allowed, however.  A false positive may result
//	** in an incorrect answer.
//	**
//	** Terms of p that are marked with EP_OuterON (and hence that come from
//	** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
//	**
//	** This routine is used to check if a LEFT JOIN can be converted into
//	** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
//	** clause requires that some column of the right table of the LEFT JOIN
//	** be non-NULL, then the LEFT JOIN can be safely converted into an
//	** ordinary join.
//	*/
func _sqlite3ExprImpliesNonNullRow(tls *libc.TLS, p uintptr, iTab int32, isRJ int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	p = _sqlite3ExprSkipCollateAndLikely(tls, p)
	if p == uintptr(0) {
		return 0
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_NOTNULL) {
		p = (*TExpr)(unsafe.Pointer(p)).FpLeft
	} else {
		for libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_AND) {
			if _sqlite3ExprImpliesNonNullRow(tls, (*TExpr)(unsafe.Pointer(p)).FpLeft, iTab, isRJ) != 0 {
				return int32(1)
			}
			p = (*TExpr)(unsafe.Pointer(p)).FpRight
		}
	}
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_impliesNotNullRow)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = uintptr(0)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback2 = uintptr(0)
	(**(**TWalker)(__ccgo_up(bp))).FeCode = uint16(0)
	(**(**TWalker)(__ccgo_up(bp))).FmWFlags = libc.BoolUint16(isRJ != 0)
	*(*int32)(unsafe.Pointer(bp + 24)) = iTab
	_sqlite3WalkExpr(tls, bp, p)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

// C documentation
//
//	/*
//	** Allocate an expression for a 32-bit signed integer literal.
//	*/
func _sqlite3ExprInt32(tls *libc.TLS, db uintptr, iVal int32) (r uintptr) {
	var pNew uintptr
	var v1 int32
	_, _ = pNew, v1
	pNew = _sqlite3DbMallocRawNN(tls, db, uint64(52))
	if pNew != 0 {
		libc.Xmemset(tls, pNew, 0, uint32(52))
		(*TExpr)(unsafe.Pointer(pNew)).Fop = uint8(TK_INTEGER)
		(*TExpr)(unsafe.Pointer(pNew)).FiAgg = int16(-int32(1))
		if iVal != 0 {
			v1 = int32(EP_IsTrue)
		} else {
			v1 = int32(EP_IsFalse)
		}
		(*TExpr)(unsafe.Pointer(pNew)).Fflags = libc.Uint32FromInt32(libc.Int32FromInt32(EP_IntValue) | libc.Int32FromInt32(EP_Leaf) | v1)
		*(*int32)(unsafe.Pointer(pNew + 8)) = iVal
		(*TExpr)(unsafe.Pointer(pNew)).FnHeight = int32(1)
	}
	return pNew
}

// C documentation
//
//	/*
//	** Walk the expression tree passed as the first argument. Return non-zero
//	** if the expression consists entirely of constants or copies of terms
//	** in pGroupBy that sort with the BINARY collation sequence.
//	**
//	** This routine is used to determine if a term of the HAVING clause can
//	** be promoted into the WHERE clause.  In order for such a promotion to work,
//	** the value of the HAVING clause term must be the same for all members of
//	** a "group".  The requirement that the GROUP BY term must be BINARY
//	** assumes that no other collating sequence will have a finer-grained
//	** grouping than binary.  In other words (A=B COLLATE binary) implies
//	** A=B in every other collating sequence.  The requirement that the
//	** GROUP BY be BINARY is stricter than necessary.  It would also work
//	** to promote HAVING clauses that use the same alternative collating
//	** sequence as the GROUP BY term, but that is much harder to check,
//	** alternative collating sequences are uncommon, and this is only an
//	** optimization, so we take the easy way out and simply require the
//	** GROUP BY to use the BINARY collating sequence.
//	*/
func _sqlite3ExprIsConstantOrGroupBy(tls *libc.TLS, pParse uintptr, p uintptr, pGroupBy uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	(**(**TWalker)(__ccgo_up(bp))).FeCode = uint16(1)
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_exprNodeIsConstantOrGroupBy)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = uintptr(0)
	*(*uintptr)(unsafe.Pointer(bp + 24)) = pGroupBy
	(**(**TWalker)(__ccgo_up(bp))).FpParse = pParse
	_sqlite3WalkExpr(tls, bp, p)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

// C documentation
//
//	/*
//	** If the expression p codes a constant integer that is small enough
//	** to fit in a 32-bit integer, return 1 and put the value of the integer
//	** in *pValue.  If the expression is not an integer or if it is too big
//	** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
//	**
//	** If the pParse pointer is provided, then allow the expression p to be
//	** a parameter (TK_VARIABLE) that is bound to an integer.
//	** But if pParse is NULL, then p must be a pure integer literal.
//	*/
func _sqlite3ExprIsInteger(tls *libc.TLS, p uintptr, pValue uintptr, pParse uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pVal uintptr
	var rc int32
	var vv Tsqlite3_int64
	var _ /* v at bp+0 */ int32
	_, _, _ = pVal, rc, vv
	rc = 0
	if p == uintptr(0) {
		return 0
	} /* Used to only happen following on OOM */
	/* If an expression is an integer literal that fits in a signed 32-bit
	 ** integer, then the EP_IntValue flag will have already been set */
	if (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_IntValue) != 0 {
		**(**int32)(__ccgo_up(pValue)) = *(*int32)(unsafe.Pointer(p + 8))
		return int32(1)
	}
	switch libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) {
	case int32(TK_UPLUS):
		rc = _sqlite3ExprIsInteger(tls, (*TExpr)(unsafe.Pointer(p)).FpLeft, pValue, uintptr(0))
	case int32(TK_UMINUS):
		**(**int32)(__ccgo_up(bp)) = 0
		if _sqlite3ExprIsInteger(tls, (*TExpr)(unsafe.Pointer(p)).FpLeft, bp, uintptr(0)) != 0 {
			**(**int32)(__ccgo_up(pValue)) = -**(**int32)(__ccgo_up(bp))
			rc = int32(1)
		}
	case int32(TK_VARIABLE):
		if pParse == uintptr(0) {
			break
		}
		if (*TParse)(unsafe.Pointer(pParse)).FpVdbe == uintptr(0) {
			break
		}
		if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Fflags&uint64(SQLITE_EnableQPSG) != uint64(0) {
			break
		}
		_sqlite3VdbeSetVarmask(tls, (*TParse)(unsafe.Pointer(pParse)).FpVdbe, int32((*TExpr)(unsafe.Pointer(p)).FiColumn))
		pVal = _sqlite3VdbeGetBoundValue(tls, (*TParse)(unsafe.Pointer(pParse)).FpReprepare, int32((*TExpr)(unsafe.Pointer(p)).FiColumn), uint8(SQLITE_AFF_BLOB))
		if pVal != 0 {
			if Xsqlite3_value_type(tls, pVal) == int32(SQLITE_INTEGER) {
				vv = Xsqlite3_value_int64(tls, pVal)
				if vv == vv&int64(0x7fffffff) { /* non-negative numbers only */
					**(**int32)(__ccgo_up(pValue)) = int32(vv)
					rc = int32(1)
				}
			}
			_sqlite3ValueFree(tls, pVal)
		}
	default:
		break
	}
	return rc
}

// C documentation
//
//	/*
//	** If pExpr is one of "like", "glob", "match", or "regexp", then
//	** return the corresponding SQLITE_INDEX_CONSTRAINT_xxxx value.
//	** If not, return 0.
//	**
//	** pExpr is guaranteed to be a TK_FUNCTION.
//	*/
func _sqlite3ExprIsLikeOperator(tls *libc.TLS, pExpr uintptr) (r int32) {
	var i int32
	_ = i
	i = 0
	for {
		if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(32)/libc.Uint32FromInt64(8))) {
			break
		}
		if _sqlite3StrICmp(tls, *(*uintptr)(unsafe.Pointer(pExpr + 8)), _aOp[i].FzOp) == 0 {
			return libc.Int32FromUint8(_aOp[i].FeOp)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** Check pExpr to see if it is an constraint on the single data source
//	** pSrc = &pSrcList->a[iSrc].  In other words, check to see if pExpr
//	** constrains pSrc but does not depend on any other tables or data
//	** sources anywhere else in the query.  Return true (non-zero) if pExpr
//	** is a constraint on pSrc only.
//	**
//	** This is an optimization.  False negatives will perhaps cause slower
//	** queries, but false positives will yield incorrect answers.  So when in
//	** doubt, return 0.
//	**
//	** To be an single-source constraint, the following must be true:
//	**
//	**   (1)  pExpr cannot refer to any table other than pSrc->iCursor.
//	**
//	**   (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is
//	**        true and the subquery is non-correlated
//	**
//	**   (2b) pExpr cannot use non-deterministic functions.
//	**
//	**   (3)  pSrc cannot be part of the left operand for a RIGHT JOIN.
//	**        (Is there some way to relax this constraint?)
//	**
//	**   (4)  If pSrc is the right operand of a LEFT JOIN, then...
//	**         (4a)  pExpr must come from an ON clause..
//	**         (4b)  and specifically the ON clause associated with the LEFT JOIN.
//	**
//	**   (5)  If pSrc is the right operand of a LEFT JOIN or the left
//	**        operand of a RIGHT JOIN, then pExpr must be from the WHERE
//	**        clause, not an ON clause.
//	**
//	**   (6) Either:
//	**
//	**       (6a) pExpr does not originate in an ON or USING clause, or
//	**
//	**       (6b) The ON or USING clause from which pExpr is derived is
//	**            not to the left of a RIGHT JOIN (or FULL JOIN).
//	**
//	**       Without this restriction, accepting pExpr as a single-table
//	**       constraint might move the the ON/USING filter expression
//	**       from the left side of a RIGHT JOIN over to the right side,
//	**       which leads to incorrect answers.  See also restriction (9)
//	**       on push-down.
//	*/
func _sqlite3ExprIsSingleTableConstraint(tls *libc.TLS, pExpr uintptr, pSrcList uintptr, iSrc int32, bAllowSubq int32) (r int32) {
	var jj int32
	var pSrc uintptr
	_, _ = jj, pSrc
	pSrc = pSrcList + 8 + uintptr(iSrc)*48
	if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSrc)).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
		return 0 /* rule (3) */
	}
	if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSrc)).Ffg.Fjointype)&int32(JT_LEFT) != 0 {
		if !((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != libc.Uint32FromInt32(0)) {
			return 0
		} /* rule (4a) */
		if *(*int32)(unsafe.Pointer(pExpr + 36)) != (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor {
			return 0
		} /* rule (4b) */
	} else {
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0) {
			return 0
		} /* rule (5) */
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON)) != uint32(0) && libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(pSrcList + 8))).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
		jj = 0
		for {
			if !(jj < iSrc) {
				break
			}
			if *(*int32)(unsafe.Pointer(pExpr + 36)) == (*(*TSrcItem)(unsafe.Pointer(pSrcList + 8 + uintptr(jj)*48))).FiCursor {
				if libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(pSrcList + 8 + uintptr(jj)*48))).Ffg.Fjointype)&int32(JT_LTORJ) != 0 {
					return 0 /* restriction (6) */
				}
				break
			}
			goto _1
		_1:
			;
			jj = jj + 1
		}
	}
	/* Rules (1), (2a), and (2b) handled by the following: */
	return _sqlite3ExprIsTableConstant(tls, pExpr, (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor, bAllowSubq)
}

// C documentation
//
//	/*
//	** Walk an expression tree.  Return non-zero if the expression is constant
//	** for any single row of the table with cursor iCur.  In other words, the
//	** expression must not refer to any non-deterministic function nor any
//	** table other than iCur.
//	**
//	** Consider uncorrelated subqueries to be constants if the bAllowSubq
//	** parameter is true.
//	*/
func _sqlite3ExprIsTableConstant(tls *libc.TLS, p uintptr, iCur int32, bAllowSubq int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var _ /* w at bp+0 */ TWalker
	(**(**TWalker)(__ccgo_up(bp))).FeCode = uint16(3)
	(**(**TWalker)(__ccgo_up(bp))).FpParse = uintptr(0)
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_exprNodeIsConstant)
	if bAllowSubq != 0 {
		(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_exprSelectWalkTableConstant)
	} else {
		(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_sqlite3SelectWalkFail)
	}
	*(*int32)(unsafe.Pointer(bp + 24)) = iCur
	_sqlite3WalkExpr(tls, bp, p)
	return libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode)
}

func _sqlite3ExprListAppendGrow(tls *libc.TLS, db uintptr, pList uintptr, pExpr uintptr) (r uintptr) {
	var pItem, pNew, v2 uintptr
	var v1 int32
	_, _, _, _ = pItem, pNew, v1, v2
	**(**int32)(__ccgo_up(pList + 4)) *= int32(2)
	pNew = _sqlite3DbRealloc(tls, db, pList, uint64(uint32(libc.UintptrFromInt32(0)+8)+libc.Uint32FromInt32((*TExprList)(unsafe.Pointer(pList)).FnAlloc)*libc.Uint32FromInt64(20)))
	if pNew == uintptr(0) {
		_sqlite3ExprListDelete(tls, db, pList)
		_sqlite3ExprDelete(tls, db, pExpr)
		return uintptr(0)
	} else {
		pList = pNew
	}
	v2 = pList
	v1 = *(*int32)(unsafe.Pointer(v2))
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	pItem = pList + 8 + uintptr(v1)*20
	**(**TExprList_item)(__ccgo_up(pItem)) = _zeroItem
	(*TExprList_item)(unsafe.Pointer(pItem)).FpExpr = pExpr
	return pList
}

func _sqlite3ExprListAppendNew(tls *libc.TLS, db uintptr, pExpr uintptr) (r uintptr) {
	var pItem, pList uintptr
	_, _ = pItem, pList
	pList = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(libc.UintptrFromInt32(0)+8)+libc.Uint32FromInt32(libc.Int32FromInt32(4))*libc.Uint32FromInt64(20)))
	if pList == uintptr(0) {
		_sqlite3ExprDelete(tls, db, pExpr)
		return uintptr(0)
	}
	(*TExprList)(unsafe.Pointer(pList)).FnAlloc = int32(4)
	(*TExprList)(unsafe.Pointer(pList)).FnExpr = int32(1)
	pItem = pList + 8
	**(**TExprList_item)(__ccgo_up(pItem)) = _zeroItem
	(*TExprList_item)(unsafe.Pointer(pItem)).FpExpr = pExpr
	return pList
}

// C documentation
//
//	/*
//	** Compare two ExprList objects.  Return 0 if they are identical, 1
//	** if they are certainly different, or 2 if it is not possible to
//	** determine if they are identical or not.
//	**
//	** If any subelement of pB has Expr.iTable==(-1) then it is allowed
//	** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
//	**
//	** This routine might return non-zero for equivalent ExprLists.  The
//	** only consequence will be disabled optimizations.  But this routine
//	** must never return 0 if the two ExprList objects are different, or
//	** a malfunction will result.
//	**
//	** Two NULL pointers are considered to be the same.  But a NULL pointer
//	** always differs from a non-NULL pointer.
//	*/
func _sqlite3ExprListCompare(tls *libc.TLS, pA uintptr, pB uintptr, iTab int32) (r int32) {
	var i, res, v2 int32
	var pExprA, pExprB uintptr
	_, _, _, _, _ = i, pExprA, pExprB, res, v2
	if pA == uintptr(0) && pB == uintptr(0) {
		return 0
	}
	if pA == uintptr(0) || pB == uintptr(0) {
		return int32(1)
	}
	if (*TExprList)(unsafe.Pointer(pA)).FnExpr != (*TExprList)(unsafe.Pointer(pB)).FnExpr {
		return int32(1)
	}
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pA)).FnExpr) {
			break
		}
		pExprA = (*(*TExprList_item)(unsafe.Pointer(pA + 8 + uintptr(i)*20))).FpExpr
		pExprB = (*(*TExprList_item)(unsafe.Pointer(pB + 8 + uintptr(i)*20))).FpExpr
		if libc.Int32FromUint8((*(*TExprList_item)(unsafe.Pointer(pA + 8 + uintptr(i)*20))).Ffg.FsortFlags) != libc.Int32FromUint8((*(*TExprList_item)(unsafe.Pointer(pB + 8 + uintptr(i)*20))).Ffg.FsortFlags) {
			return int32(1)
		}
		v2 = _sqlite3ExprCompare(tls, uintptr(0), pExprA, pExprB, iTab)
		res = v2
		if v2 != 0 {
			return res
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

func _sqlite3ExprListDup(tls *libc.TLS, db uintptr, p uintptr, flags int32) (r uintptr) {
	var i int32
	var pItem, pNew, pNewExpr, pOldExpr, pOldItem, pPriorSelectColNew, pPriorSelectColOld, v2 uintptr
	var v3 bool
	_, _, _, _, _, _, _, _, _, _ = i, pItem, pNew, pNewExpr, pOldExpr, pOldItem, pPriorSelectColNew, pPriorSelectColOld, v2, v3
	pPriorSelectColOld = uintptr(0)
	pPriorSelectColNew = uintptr(0)
	if p == uintptr(0) {
		return uintptr(0)
	}
	pNew = _sqlite3DbMallocRawNN(tls, db, libc.Uint64FromInt32(_sqlite3DbMallocSize(tls, db, p)))
	if pNew == uintptr(0) {
		return uintptr(0)
	}
	(*TExprList)(unsafe.Pointer(pNew)).FnExpr = (*TExprList)(unsafe.Pointer(p)).FnExpr
	(*TExprList)(unsafe.Pointer(pNew)).FnAlloc = (*TExprList)(unsafe.Pointer(p)).FnAlloc
	pItem = pNew + 8
	pOldItem = p + 8
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(p)).FnExpr) {
			break
		}
		pOldExpr = (*TExprList_item)(unsafe.Pointer(pOldItem)).FpExpr
		(*TExprList_item)(unsafe.Pointer(pItem)).FpExpr = _sqlite3ExprDup(tls, db, pOldExpr, flags)
		if v3 = pOldExpr != 0 && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pOldExpr)).Fop) == int32(TK_SELECT_COLUMN); v3 {
			v2 = (*TExprList_item)(unsafe.Pointer(pItem)).FpExpr
			pNewExpr = v2
		}
		if v3 && v2 != uintptr(0) {
			if (*TExpr)(unsafe.Pointer(pNewExpr)).FpRight != 0 {
				pPriorSelectColOld = (*TExpr)(unsafe.Pointer(pOldExpr)).FpRight
				pPriorSelectColNew = (*TExpr)(unsafe.Pointer(pNewExpr)).FpRight
				(*TExpr)(unsafe.Pointer(pNewExpr)).FpLeft = (*TExpr)(unsafe.Pointer(pNewExpr)).FpRight
			} else {
				if (*TExpr)(unsafe.Pointer(pOldExpr)).FpLeft != pPriorSelectColOld {
					pPriorSelectColOld = (*TExpr)(unsafe.Pointer(pOldExpr)).FpLeft
					pPriorSelectColNew = _sqlite3ExprDup(tls, db, pPriorSelectColOld, flags)
					(*TExpr)(unsafe.Pointer(pNewExpr)).FpRight = pPriorSelectColNew
				}
				(*TExpr)(unsafe.Pointer(pNewExpr)).FpLeft = pPriorSelectColNew
			}
		}
		(*TExprList_item)(unsafe.Pointer(pItem)).FzEName = _sqlite3DbStrDup(tls, db, (*TExprList_item)(unsafe.Pointer(pOldItem)).FzEName)
		(*TExprList_item)(unsafe.Pointer(pItem)).Ffg = (*TExprList_item)(unsafe.Pointer(pOldItem)).Ffg
		(*TExprList_item)(unsafe.Pointer(pItem)).Fu = (*TExprList_item)(unsafe.Pointer(pOldItem)).Fu
		goto _1
	_1:
		;
		i = i + 1
		pItem += 20
		pOldItem += 20
	}
	return pNew
}

// C documentation
//
//	/*
//	** Set the ExprList.a[].zEName element of the most recently added item
//	** on the expression list.
//	**
//	** pList might be NULL following an OOM error.  But pName should never be
//	** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
//	** is set.
//	*/
func _sqlite3ExprListSetName(tls *libc.TLS, pParse uintptr, pList uintptr, pName uintptr, dequote int32) {
	var pItem uintptr
	_ = pItem
	if pList != 0 {
		pItem = pList + 8 + uintptr((*TExprList)(unsafe.Pointer(pList)).FnExpr-int32(1))*20
		(*TExprList_item)(unsafe.Pointer(pItem)).FzEName = _sqlite3DbStrNDup(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, (*TToken)(unsafe.Pointer(pName)).Fz, uint64((*TToken)(unsafe.Pointer(pName)).Fn))
		if dequote != 0 {
			/* If dequote==0, then pName->z does not point to part of a DDL
			 ** statement handled by the parser. And so no token need be added
			 ** to the token-map.  */
			_sqlite3Dequote(tls, (*TExprList_item)(unsafe.Pointer(pItem)).FzEName)
			if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) >= int32(PARSE_MODE_RENAME) {
				_sqlite3RenameTokenMap(tls, pParse, (*TExprList_item)(unsafe.Pointer(pItem)).FzEName, pName)
			}
		}
	}
}

// C documentation
//
//	/*
//	** Set the sort order for the last element on the given ExprList.
//	*/
func _sqlite3ExprListSetSortOrder(tls *libc.TLS, p uintptr, iSortOrder int32, eNulls int32) {
	var pItem, v1 uintptr
	_, _ = pItem, v1
	if p == uintptr(0) {
		return
	}
	pItem = p + 8 + uintptr((*TExprList)(unsafe.Pointer(p)).FnExpr-int32(1))*20
	if iSortOrder == -int32(1) {
		iSortOrder = SQLITE_SO_ASC
	}
	(*TExprList_item)(unsafe.Pointer(pItem)).Ffg.FsortFlags = libc.Uint8FromInt32(iSortOrder)
	if eNulls != -int32(1) {
		libc.SetBitFieldPtr16Uint32(pItem+8+4, libc.Uint32FromInt32(1), 5, 0x20)
		if iSortOrder != eNulls {
			v1 = pItem + 8
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(KEYINFO_ORDER_BIGNULL))
		}
	}
}

// C documentation
//
//	/*
//	** Make arrangements to invoke OP_Null on a range of registers
//	** during initialization.
//	*/
func _sqlite3ExprNullRegisterRange(tls *libc.TLS, pParse uintptr, iReg int32, nReg int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var okConstFactor Tu8
	var _ /* t at bp+0 */ TExpr
	_ = okConstFactor
	okConstFactor = libc.Uint8FromInt32(int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28)) & 0x80 >> 7)))
	libc.Xmemset(tls, bp, 0, uint32(52))
	(**(**TExpr)(__ccgo_up(bp))).Fop = uint8(TK_NULLS)
	*(*int32)(unsafe.Pointer(bp + 44)) = nReg
	libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(1), 7, 0x80)
	_sqlite3ExprCodeRunJustOnce(tls, pParse, bp, iReg)
	libc.SetBitFieldPtr16Uint32(pParse+28, uint32(okConstFactor), 7, 0x80)
}

// C documentation
//
//	/*
//	** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
//	** only columns that are modified by the UPDATE are those for which
//	** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
//	**
//	** Return true if CHECK constraint pExpr uses any of the
//	** changing columns (or the rowid if it is changing).  In other words,
//	** return true if this CHECK constraint must be validated for
//	** the new row in the UPDATE statement.
//	**
//	** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
//	** The operation of this routine is the same - return true if an only if
//	** the expression uses one or more of columns identified by the second and
//	** third arguments.
//	*/
func _sqlite3ExprReferencesUpdatedColumn(tls *libc.TLS, pExpr uintptr, aiChng uintptr, chngRowid int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var v1 uintptr
	var _ /* w at bp+0 */ TWalker
	_ = v1
	libc.Xmemset(tls, bp, 0, uint32(28))
	(**(**TWalker)(__ccgo_up(bp))).FeCode = uint16(0)
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_checkConstraintExprNode)
	*(*uintptr)(unsafe.Pointer(bp + 24)) = aiChng
	_sqlite3WalkExpr(tls, bp, pExpr)
	if !(chngRowid != 0) {
		v1 = bp + 20
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(CKCNSTRNT_ROWID))
	}
	return libc.BoolInt32(libc.Int32FromUint16((**(**TWalker)(__ccgo_up(bp))).FeCode) != 0)
}

// C documentation
//
//	/*
//	** Set the error offset for an Expr node, if possible.
//	*/
func _sqlite3ExprSetErrorOffset(tls *libc.TLS, pExpr uintptr, iOfst int32) {
	if pExpr == uintptr(0) {
		return
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_InnerON)|libc.Int32FromInt32(EP_OuterON)) != uint32(0) {
		return
	}
	*(*int32)(unsafe.Pointer(pExpr + 36)) = iOfst
}

// C documentation
//
//	/*
//	** Skip over any TK_COLLATE operators and/or any unlikely()
//	** or likelihood() or likely() functions at the root of an
//	** expression.
//	*/
func _sqlite3ExprSkipCollateAndLikely(tls *libc.TLS, pExpr uintptr) (r uintptr) {
	for pExpr != 0 && (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Skip)|libc.Int32FromInt32(EP_Unlikely)) != uint32(0) {
		if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Unlikely)) != uint32(0) {
			pExpr = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)) + 8))).FpExpr
		} else {
			if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLLATE) {
				pExpr = (*TExpr)(unsafe.Pointer(pExpr)).FpLeft
			} else {
				break
			}
		}
	}
	return pExpr
}

// C documentation
//
//	/*
//	** If the expression passed as the only argument is of type TK_VECTOR
//	** return the number of expressions in the vector. Or, if the expression
//	** is a sub-select, return the number of columns in the sub-select. For
//	** any other type of expression, return 1.
//	*/
func _sqlite3ExprVectorSize(tls *libc.TLS, pExpr uintptr) (r int32) {
	var op Tu8
	_ = op
	op = (*TExpr)(unsafe.Pointer(pExpr)).Fop
	if libc.Int32FromUint8(op) == int32(TK_REGISTER) {
		op = (*TExpr)(unsafe.Pointer(pExpr)).Fop2
	}
	if libc.Int32FromUint8(op) == int32(TK_VECTOR) {
		return (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FnExpr
	} else {
		if libc.Int32FromUint8(op) == int32(TK_SELECT) {
			return (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FpEList)).FnExpr
		} else {
			return int32(1)
		}
	}
	return r
}

// C documentation
//
//	/*
//	** Parameter zName points to a UTF-8 encoded string nName bytes long.
//	** Return the CollSeq* pointer for the collation sequence named zName
//	** for the encoding 'enc' from the database 'db'.
//	**
//	** If the entry specified is not found and 'create' is true, then create a
//	** new entry.  Otherwise return NULL.
//	**
//	** A separate function sqlite3LocateCollSeq() is a wrapper around
//	** this routine.  sqlite3LocateCollSeq() invokes the collation factory
//	** if necessary and generates an error message if the collating sequence
//	** cannot be found.
//	**
//	** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
//	*/
func _sqlite3FindCollSeq(tls *libc.TLS, db uintptr, enc Tu8, zName uintptr, create int32) (r uintptr) {
	var pColl uintptr
	_ = pColl
	if zName != 0 {
		pColl = _findCollSeqEntry(tls, db, zName, create)
		if pColl != 0 {
			pColl = pColl + uintptr(libc.Int32FromUint8(enc)-int32(1))*20
		}
	} else {
		pColl = (*Tsqlite3)(unsafe.Pointer(db)).FpDfltColl
	}
	return pColl
}

// C documentation
//
//	/*
//	** This routine is called after a single SQL statement has been
//	** parsed and a VDBE program to execute that statement has been
//	** prepared.  This routine puts the finishing touches on the
//	** VDBE program and resets the pParse structure for the next
//	** parse.
//	**
//	** Note that if an error occurred, it might be the case that
//	** no VDBE code was generated.
//	*/
func _sqlite3FinishCoding(tls *libc.TLS, pParse uintptr) {
	var addrRewind, i, iDb, reg, v2 int32
	var db, pEL, pRet, pReturning, pSchema, v, vtab uintptr
	_, _, _, _, _, _, _, _, _, _, _, _ = addrRewind, db, i, iDb, pEL, pRet, pReturning, pSchema, reg, v, vtab, v2
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	if (*TParse)(unsafe.Pointer(pParse)).Fnested != 0 {
		return
	}
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
			(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
		}
		return
	}
	/* Begin by generating some termination code at the end of the
	 ** vdbe program
	 */
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	if v == uintptr(0) {
		if (*Tsqlite3)(unsafe.Pointer(db)).Finit1.Fbusy != 0 {
			(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_DONE)
			return
		}
		v = _sqlite3GetVdbe(tls, pParse)
		if v == uintptr(0) {
			(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_ERROR)
		}
	}
	if v != 0 {
		if int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x8>>3)) != 0 {
			pReturning = (*(*struct {
				FpReturning uintptr
			})(unsafe.Pointer(&(*TParse)(unsafe.Pointer(pParse)).Fu1))).FpReturning
			if (*TReturning)(unsafe.Pointer(pReturning)).FnRetCol != 0 {
				_sqlite3VdbeAddOp0(tls, v, int32(OP_FkCheck))
				addrRewind = _sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (*TReturning)(unsafe.Pointer(pReturning)).FiRetCur)
				reg = (*TReturning)(unsafe.Pointer(pReturning)).FiRetReg
				i = 0
				for {
					if !(i < (*TReturning)(unsafe.Pointer(pReturning)).FnRetCol) {
						break
					}
					_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), (*TReturning)(unsafe.Pointer(pReturning)).FiRetCur, i, reg+i)
					goto _1
				_1:
					;
					i = i + 1
				}
				_sqlite3VdbeAddOp2(tls, v, int32(OP_ResultRow), reg, i)
				_sqlite3VdbeAddOp2(tls, v, int32(OP_Next), (*TReturning)(unsafe.Pointer(pReturning)).FiRetCur, addrRewind+int32(1))
				_sqlite3VdbeJumpHere(tls, v, addrRewind)
			}
		}
		_sqlite3VdbeAddOp0(tls, v, int32(OP_Halt))
		/* The cookie mask contains one bit for each database file open.
		 ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
		 ** set for each database that is used.  Generate code to start a
		 ** transaction on each used database and to verify the schema cookie
		 ** on each used database.
		 */
		_sqlite3VdbeJumpHere(tls, v, 0)
		iDb = 0
		for {
			if libc.BoolInt32((*TParse)(unsafe.Pointer(pParse)).FcookieMask&(libc.Uint32FromInt32(1)<<iDb) != uint32(0)) == 0 {
				goto _3
			}
			_sqlite3VdbeUsesBtree(tls, v, iDb)
			pSchema = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema
			_sqlite3VdbeAddOp4Int(tls, v, int32(OP_Transaction), iDb, libc.BoolInt32((*TParse)(unsafe.Pointer(pParse)).FwriteMask&(libc.Uint32FromInt32(1)<<iDb) != uint32(0)), (*TSchema)(unsafe.Pointer(pSchema)).Fschema_cookie, (*TSchema)(unsafe.Pointer(pSchema)).FiGeneration)
			if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).Finit1.Fbusy) == 0 {
				_sqlite3VdbeChangeP5(tls, v, uint16(1))
			}
			goto _3
		_3:
			;
			iDb = iDb + 1
			v2 = iDb
			if !(v2 < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
				break
			}
		}
		i = 0
		for {
			if !(i < (*TParse)(unsafe.Pointer(pParse)).FnVtabLock) {
				break
			}
			vtab = _sqlite3GetVTable(tls, db, **(**uintptr)(__ccgo_up((*TParse)(unsafe.Pointer(pParse)).FapVtabLock + uintptr(i)*4)))
			_sqlite3VdbeAddOp4(tls, v, int32(OP_VBegin), 0, 0, 0, vtab, -int32(12))
			goto _4
		_4:
			;
			i = i + 1
		}
		(*TParse)(unsafe.Pointer(pParse)).FnVtabLock = 0
		/* Once all the cookies have been verified and transactions opened,
		 ** obtain the required table-locks. This is a no-op unless the
		 ** shared-cache feature is enabled.
		 */
		if (*TParse)(unsafe.Pointer(pParse)).FnTableLock != 0 {
			_codeTableLocks(tls, pParse)
		}
		/* Initialize any AUTOINCREMENT data structures required.
		 */
		if (*TParse)(unsafe.Pointer(pParse)).FpAinc != 0 {
			_sqlite3AutoincrementBegin(tls, pParse)
		}
		/* Code constant expressions that were factored out of inner loops.
		 */
		if (*TParse)(unsafe.Pointer(pParse)).FpConstExpr != 0 {
			pEL = (*TParse)(unsafe.Pointer(pParse)).FpConstExpr
			libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(0), 7, 0x80)
			i = 0
			for {
				if !(i < (*TExprList)(unsafe.Pointer(pEL)).FnExpr) {
					break
				}
				_sqlite3ExprCode(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pEL + 8 + uintptr(i)*20))).FpExpr, *(*int32)(unsafe.Pointer(pEL + 8 + uintptr(i)*20 + 16)))
				goto _5
			_5:
				;
				i = i + 1
			}
		}
		if int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x8>>3)) != 0 {
			pRet = (*(*struct {
				FpReturning uintptr
			})(unsafe.Pointer(&(*TParse)(unsafe.Pointer(pParse)).Fu1))).FpReturning
			if (*TReturning)(unsafe.Pointer(pRet)).FnRetCol != 0 {
				_sqlite3VdbeAddOp2(tls, v, int32(OP_OpenEphemeral), (*TReturning)(unsafe.Pointer(pRet)).FiRetCur, (*TReturning)(unsafe.Pointer(pRet)).FnRetCol)
			}
		}
		/* Finally, jump back to the beginning of the executable code. */
		_sqlite3VdbeGoto(tls, v, int32(1))
	}
	/* Get the VDBE program ready for execution
	 */
	if (*TParse)(unsafe.Pointer(pParse)).FnErr == 0 {
		/* A minimum of one cursor is required if autoincrement is used
		 *  See ticket [a696379c1f08866] */
		_sqlite3VdbeMakeReady(tls, v, pParse)
		(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_DONE)
	} else {
		(*TParse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_ERROR)
	}
}

// C documentation
//
//	/*
//	** This function is called when inserting, deleting or updating a row of
//	** table pTab to generate VDBE code to perform foreign key constraint
//	** processing for the operation.
//	**
//	** For a DELETE operation, parameter regOld is passed the index of the
//	** first register in an array of (pTab->nCol+1) registers containing the
//	** rowid of the row being deleted, followed by each of the column values
//	** of the row being deleted, from left to right. Parameter regNew is passed
//	** zero in this case.
//	**
//	** For an INSERT operation, regOld is passed zero and regNew is passed the
//	** first register of an array of (pTab->nCol+1) registers containing the new
//	** row data.
//	**
//	** For an UPDATE operation, this function is called twice. Once before
//	** the original record is deleted from the table using the calling convention
//	** described for DELETE. Then again after the original record is deleted
//	** but before the new record is inserted using the INSERT convention.
//	*/
func _sqlite3FkCheck(tls *libc.TLS, pParse uintptr, pTab uintptr, regOld int32, regNew int32, aChange uintptr, bChngRowid int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var aiCol, db, pFKey, pItem, pSrc, pTo, v, zCol, zDb, v7 uintptr
	var bIgnore, eAction, i, iDb, iFromCol, iJump, iReg, isIgnoreErrors, rcauth, v4 int32
	var _ /* aiCol at bp+16 */ uintptr
	var _ /* aiFree at bp+4 */ uintptr
	var _ /* iCol at bp+8 */ int32
	var _ /* pIdx at bp+0 */ uintptr
	var _ /* pIdx at bp+12 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aiCol, bIgnore, db, eAction, i, iDb, iFromCol, iJump, iReg, isIgnoreErrors, pFKey, pItem, pSrc, pTo, rcauth, v, zCol, zDb, v4, v7
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb /* Name of database containing pTab */
	isIgnoreErrors = int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28)) & 0x1 >> 0))
	/* Exactly one of regOld and regNew should be non-zero. */
	/* If foreign-keys are disabled, this function is a no-op. */
	if (*Tsqlite3)(unsafe.Pointer(db)).Fflags&uint64(SQLITE_ForeignKeys) == uint64(0) {
		return
	}
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_NORM)) {
		return
	}
	iDb = _sqlite3SchemaToIndex(tls, db, (*TTable)(unsafe.Pointer(pTab)).FpSchema)
	zDb = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName
	/* Loop through all the foreign key constraints for which pTab is the
	 ** child table (the table that the foreign key definition is part of).  */
	pFKey = (*(*struct {
		FaddColOffset int32
		FpFKey        uintptr
		FpDfltList    uintptr
	})(unsafe.Pointer(pTab + 44))).FpFKey
	for {
		if !(pFKey != 0) {
			break
		} /* Parent table of foreign key pFKey */
		**(**uintptr)(__ccgo_up(bp)) = uintptr(0) /* Index on key columns in pTo */
		**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
		bIgnore = 0
		if aChange != 0 && Xsqlite3_stricmp(tls, (*TTable)(unsafe.Pointer(pTab)).FzName, (*TFKey)(unsafe.Pointer(pFKey)).FzTo) != 0 && _fkChildIsModified(tls, pTab, pFKey, aChange, bChngRowid) == 0 {
			goto _1
		}
		/* Find the parent table of this foreign key. Also find a unique index
		 ** on the parent key columns in the parent table. If either of these
		 ** schema items cannot be located, set an error in pParse and return
		 ** early.  */
		if int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x1>>0)) != 0 {
			pTo = _sqlite3FindTable(tls, db, (*TFKey)(unsafe.Pointer(pFKey)).FzTo, zDb)
		} else {
			pTo = _sqlite3LocateTable(tls, pParse, uint32(0), (*TFKey)(unsafe.Pointer(pFKey)).FzTo, zDb)
		}
		if !(pTo != 0) || _sqlite3FkLocateIndex(tls, pParse, pTo, pFKey, bp, bp+4) != 0 {
			if !(isIgnoreErrors != 0) || (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
				return
			}
			if pTo == uintptr(0) {
				/* If isIgnoreErrors is true, then a table is being dropped. In this
				 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
				 ** before actually dropping it in order to check FK constraints.
				 ** If the parent table of an FK constraint on the current table is
				 ** missing, behave as if it is empty. i.e. decrement the relevant
				 ** FK counter for each row of the current table with non-NULL keys.
				 */
				v = _sqlite3GetVdbe(tls, pParse)
				iJump = _sqlite3VdbeCurrentAddr(tls, v) + (*TFKey)(unsafe.Pointer(pFKey)).FnCol + int32(1)
				i = 0
				for {
					if !(i < (*TFKey)(unsafe.Pointer(pFKey)).FnCol) {
						break
					}
					iFromCol = (*(*TsColMap)(unsafe.Pointer(pFKey + 36 + uintptr(i)*8))).FiFrom
					iReg = int32(_sqlite3TableColumnToStorage(tls, (*TFKey)(unsafe.Pointer(pFKey)).FpFrom, int16(iFromCol))) + regOld + int32(1)
					_sqlite3VdbeAddOp2(tls, v, int32(OP_IsNull), iReg, iJump)
					goto _2
				_2:
					;
					i = i + 1
				}
				_sqlite3VdbeAddOp2(tls, v, int32(OP_FkCounter), libc.Int32FromUint8((*TFKey)(unsafe.Pointer(pFKey)).FisDeferred), -int32(1))
			}
			goto _1
		}
		if **(**uintptr)(__ccgo_up(bp + 4)) != 0 {
			aiCol = **(**uintptr)(__ccgo_up(bp + 4))
		} else {
			**(**int32)(__ccgo_up(bp + 8)) = (*(*TsColMap)(unsafe.Pointer(pFKey + 36))).FiFrom
			aiCol = bp + 8
		}
		i = 0
		for {
			if !(i < (*TFKey)(unsafe.Pointer(pFKey)).FnCol) {
				break
			}
			if **(**int32)(__ccgo_up(aiCol + uintptr(i)*4)) == int32((*TTable)(unsafe.Pointer(pTab)).FiPKey) {
				**(**int32)(__ccgo_up(aiCol + uintptr(i)*4)) = -int32(1)
			}
			/* Request permission to read the parent key columns. If the
			 ** authorization callback returns SQLITE_IGNORE, behave as if any
			 ** values read from the parent table are NULL. */
			if (*Tsqlite3)(unsafe.Pointer(db)).FxAuth != 0 {
				if **(**uintptr)(__ccgo_up(bp)) != 0 {
					v4 = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaiColumn + uintptr(i)*2)))
				} else {
					v4 = int32((*TTable)(unsafe.Pointer(pTo)).FiPKey)
				}
				zCol = (**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTo)).FaCol + uintptr(v4)*12))).FzCnName
				rcauth = _sqlite3AuthReadCol(tls, pParse, (*TTable)(unsafe.Pointer(pTo)).FzName, zCol, iDb)
				bIgnore = libc.BoolInt32(rcauth == int32(SQLITE_IGNORE))
			}
			goto _3
		_3:
			;
			i = i + 1
		}
		/* Take a shared-cache advisory read-lock on the parent table. Allocate
		 ** a cursor to use to search the unique index on the parent key columns
		 ** in the parent table.  */
		_sqlite3TableLock(tls, pParse, iDb, (*TTable)(unsafe.Pointer(pTo)).Ftnum, uint8(0), (*TTable)(unsafe.Pointer(pTo)).FzName)
		(*TParse)(unsafe.Pointer(pParse)).FnTab = (*TParse)(unsafe.Pointer(pParse)).FnTab + 1
		if regOld != 0 {
			/* A row is being removed from the child table. Search for the parent.
			 ** If the parent does not exist, removing the child row resolves an
			 ** outstanding foreign key constraint violation. */
			_fkLookupParent(tls, pParse, iDb, pTo, **(**uintptr)(__ccgo_up(bp)), pFKey, aiCol, regOld, -int32(1), bIgnore)
		}
		if regNew != 0 && !(_isSetNullAction(tls, pParse, pFKey) != 0) {
			/* A row is being added to the child table. If a parent row cannot
			 ** be found, adding the child row has violated the FK constraint.
			 **
			 ** If this operation is being performed as part of a trigger program
			 ** that is actually a "SET NULL" action belonging to this very
			 ** foreign key, then omit this scan altogether. As all child key
			 ** values are guaranteed to be NULL, it is not possible for adding
			 ** this row to cause an FK violation.  */
			_fkLookupParent(tls, pParse, iDb, pTo, **(**uintptr)(__ccgo_up(bp)), pFKey, aiCol, regNew, +libc.Int32FromInt32(1), bIgnore)
		}
		_sqlite3DbFree(tls, db, **(**uintptr)(__ccgo_up(bp + 4)))
		goto _1
	_1:
		;
		pFKey = (*TFKey)(unsafe.Pointer(pFKey)).FpNextFrom
	}
	/* Loop through all the foreign key constraints that refer to this table.
	 ** (the "child" constraints) */
	pFKey = _sqlite3FkReferences(tls, pTab)
	for {
		if !(pFKey != 0) {
			break
		}
		**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
		**(**uintptr)(__ccgo_up(bp + 16)) = uintptr(0)
		if aChange != 0 && _fkParentIsModified(tls, pTab, pFKey, aChange, bChngRowid) == 0 {
			goto _5
		}
		if !((*TFKey)(unsafe.Pointer(pFKey)).FisDeferred != 0) && !((*Tsqlite3)(unsafe.Pointer(db)).Fflags&libc.Uint64FromInt32(SQLITE_DeferFKs) != 0) && !((*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0) && !((*TParse)(unsafe.Pointer(pParse)).FisMultiWrite != 0) {
			/* Inserting a single row into a parent table cannot cause (or fix)
			 ** an immediate foreign key violation. So do nothing in this case.  */
			goto _5
		}
		if _sqlite3FkLocateIndex(tls, pParse, pTab, pFKey, bp+12, bp+16) != 0 {
			if !(isIgnoreErrors != 0) || (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
				return
			}
			goto _5
		}
		/* Create a SrcList structure containing the child table.  We need the
		 ** child table as a SrcList for sqlite3WhereBegin() */
		pSrc = _sqlite3SrcListAppend(tls, pParse, uintptr(0), uintptr(0), uintptr(0))
		if pSrc != 0 {
			pItem = pSrc + 8
			(*TSrcItem)(unsafe.Pointer(pItem)).FpSTab = (*TFKey)(unsafe.Pointer(pFKey)).FpFrom
			(*TSrcItem)(unsafe.Pointer(pItem)).FzName = (*TTable)(unsafe.Pointer((*TFKey)(unsafe.Pointer(pFKey)).FpFrom)).FzName
			(*TTable)(unsafe.Pointer((*TSrcItem)(unsafe.Pointer(pItem)).FpSTab)).FnTabRef = (*TTable)(unsafe.Pointer((*TSrcItem)(unsafe.Pointer(pItem)).FpSTab)).FnTabRef + 1
			v7 = pParse + 44
			v4 = *(*int32)(unsafe.Pointer(v7))
			*(*int32)(unsafe.Pointer(v7)) = *(*int32)(unsafe.Pointer(v7)) + 1
			(*TSrcItem)(unsafe.Pointer(pItem)).FiCursor = v4
			if regNew != 0 {
				_fkScanChildren(tls, pParse, pSrc, pTab, **(**uintptr)(__ccgo_up(bp + 12)), pFKey, **(**uintptr)(__ccgo_up(bp + 16)), regNew, -int32(1))
			}
			if regOld != 0 {
				eAction = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pFKey + 25 + libc.BoolUintptr(aChange != uintptr(0)))))
				if (*Tsqlite3)(unsafe.Pointer(db)).Fflags&(libc.Uint64FromInt32(libc.Int32FromInt32(0x00008))<<libc.Int32FromInt32(32)) != 0 {
					eAction = OE_None
				}
				_fkScanChildren(tls, pParse, pSrc, pTab, **(**uintptr)(__ccgo_up(bp + 12)), pFKey, **(**uintptr)(__ccgo_up(bp + 16)), regOld, int32(1))
				/* If this is a deferred FK constraint, or a CASCADE or SET NULL
				 ** action applies, then any foreign key violations caused by
				 ** removing the parent key will be rectified by the action trigger.
				 ** So do not set the "may-abort" flag in this case.
				 **
				 ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
				 ** may-abort flag will eventually be set on this statement anyway
				 ** (when this function is called as part of processing the UPDATE
				 ** within the action trigger).
				 **
				 ** Note 2: At first glance it may seem like SQLite could simply omit
				 ** all OP_FkCounter related scans when either CASCADE or SET NULL
				 ** applies. The trouble starts if the CASCADE or SET NULL action
				 ** trigger causes other triggers or action rules attached to the
				 ** child table to fire. In these cases the fk constraint counters
				 ** might be set incorrectly if any OP_FkCounter related scans are
				 ** omitted.  */
				if !((*TFKey)(unsafe.Pointer(pFKey)).FisDeferred != 0) && eAction != int32(OE_Cascade) && eAction != int32(OE_SetNull) {
					_sqlite3MayAbort(tls, pParse)
				}
			}
			(*TSrcItem)(unsafe.Pointer(pItem)).FzName = uintptr(0)
			_sqlite3SrcListDelete(tls, db, pSrc)
		}
		_sqlite3DbFree(tls, db, **(**uintptr)(__ccgo_up(bp + 16)))
		goto _5
	_5:
		;
		pFKey = (*TFKey)(unsafe.Pointer(pFKey)).FpNextTo
	}
}

// C documentation
//
//	/*
//	** Clear the apTrigger[] cache of CASCADE triggers for all foreign keys
//	** in a particular database.  This needs to happen when the schema
//	** changes.
//	*/
func _sqlite3FkClearTriggerCache(tls *libc.TLS, db uintptr, iDb int32) {
	var k, pFKey, pHash, pTab uintptr
	_, _, _, _ = k, pFKey, pHash, pTab
	pHash = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema + 8
	k = (*THash)(unsafe.Pointer(pHash)).Ffirst
	for {
		if !(k != 0) {
			break
		}
		pTab = (*THashElem)(unsafe.Pointer(k)).Fdata
		if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_NORM)) {
			goto _1
		}
		pFKey = (*(*struct {
			FaddColOffset int32
			FpFKey        uintptr
			FpDfltList    uintptr
		})(unsafe.Pointer(pTab + 44))).FpFKey
		for {
			if !(pFKey != 0) {
				break
			}
			_fkTriggerDelete(tls, db, **(**uintptr)(__ccgo_up(pFKey + 28)))
			**(**uintptr)(__ccgo_up(pFKey + 28)) = uintptr(0)
			_fkTriggerDelete(tls, db, **(**uintptr)(__ccgo_up(pFKey + 28 + 1*4)))
			**(**uintptr)(__ccgo_up(pFKey + 28 + 1*4)) = uintptr(0)
			goto _2
		_2:
			;
			pFKey = (*TFKey)(unsafe.Pointer(pFKey)).FpNextFrom
		}
		goto _1
	_1:
		;
		k = (*THashElem)(unsafe.Pointer(k)).Fnext
	}
}

// C documentation
//
//	/*
//	** This function is called to generate code that runs when table pTab is
//	** being dropped from the database. The SrcList passed as the second argument
//	** to this function contains a single entry guaranteed to resolve to
//	** table pTab.
//	**
//	** Normally, no code is required. However, if either
//	**
//	**   (a) The table is the parent table of a FK constraint, or
//	**   (b) The table is the child table of a deferred FK constraint and it is
//	**       determined at runtime that there are outstanding deferred FK
//	**       constraint violations in the database,
//	**
//	** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
//	** the table from the database. Triggers are disabled while running this
//	** DELETE, but foreign key actions are not.
//	*/
func _sqlite3FkDropTable(tls *libc.TLS, pParse uintptr, pName uintptr, pTab uintptr) {
	var db, p, v uintptr
	var iSkip int32
	_, _, _, _ = db, iSkip, p, v
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	if (*Tsqlite3)(unsafe.Pointer(db)).Fflags&uint64(SQLITE_ForeignKeys) != 0 && libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == TABTYP_NORM {
		iSkip = 0
		v = _sqlite3GetVdbe(tls, pParse)
		/* VDBE has already been allocated */
		if _sqlite3FkReferences(tls, pTab) == uintptr(0) {
			p = (*(*struct {
				FaddColOffset int32
				FpFKey        uintptr
				FpDfltList    uintptr
			})(unsafe.Pointer(pTab + 44))).FpFKey
			for {
				if !(p != 0) {
					break
				}
				if (*TFKey)(unsafe.Pointer(p)).FisDeferred != 0 || (*Tsqlite3)(unsafe.Pointer(db)).Fflags&uint64(SQLITE_DeferFKs) != 0 {
					break
				}
				goto _1
			_1:
				;
				p = (*TFKey)(unsafe.Pointer(p)).FpNextFrom
			}
			if !(p != 0) {
				return
			}
			iSkip = _sqlite3VdbeMakeLabel(tls, pParse)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_FkIfZero), int32(1), iSkip)
		}
		libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(1), 0, 0x1)
		_sqlite3DeleteFrom(tls, pParse, _sqlite3SrcListDup(tls, db, pName, 0), uintptr(0), uintptr(0), uintptr(0))
		libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(0), 0, 0x1)
		/* If the DELETE has generated immediate foreign key constraint
		 ** violations, halt the VDBE and return an error at this point, before
		 ** any modifications to the schema are made. This is because statement
		 ** transactions are not able to rollback schema changes.
		 **
		 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
		 ** the statement transaction will not be rolled back even if FK
		 ** constraints are violated.
		 */
		if (*Tsqlite3)(unsafe.Pointer(db)).Fflags&uint64(SQLITE_DeferFKs) == uint64(0) {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_FkIfZero), 0, _sqlite3VdbeCurrentAddr(tls, v)+int32(2))
			_sqlite3HaltConstraint(tls, pParse, libc.Int32FromInt32(SQLITE_CONSTRAINT)|libc.Int32FromInt32(3)<<libc.Int32FromInt32(8), int32(OE_Abort), uintptr(0), int8(-libc.Int32FromInt32(1)), uint8(P5_ConstraintFK))
		}
		if iSkip != 0 {
			_sqlite3VdbeResolveLabel(tls, v, iSkip)
		}
	}
}

// C documentation
//
//	/*
//	** This function is called before generating code to update or delete a
//	** row contained in table pTab.
//	*/
func _sqlite3FkOldmask(tls *libc.TLS, pParse uintptr, pTab uintptr) (r Tu32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i int32
	var mask Tu32
	var p uintptr
	var v3 uint32
	var _ /* pIdx at bp+0 */ uintptr
	_, _, _, _ = i, mask, p, v3
	mask = uint32(0)
	if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Fflags&uint64(SQLITE_ForeignKeys) != 0 && libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == TABTYP_NORM {
		p = (*(*struct {
			FaddColOffset int32
			FpFKey        uintptr
			FpDfltList    uintptr
		})(unsafe.Pointer(pTab + 44))).FpFKey
		for {
			if !(p != 0) {
				break
			}
			i = 0
			for {
				if !(i < (*TFKey)(unsafe.Pointer(p)).FnCol) {
					break
				}
				if (*(*TsColMap)(unsafe.Pointer(p + 36 + uintptr(i)*8))).FiFrom > int32(31) {
					v3 = uint32(0xffffffff)
				} else {
					v3 = libc.Uint32FromInt32(1) << (*(*TsColMap)(unsafe.Pointer(p + 36 + uintptr(i)*8))).FiFrom
				}
				mask = mask | v3
				goto _2
			_2:
				;
				i = i + 1
			}
			goto _1
		_1:
			;
			p = (*TFKey)(unsafe.Pointer(p)).FpNextFrom
		}
		p = _sqlite3FkReferences(tls, pTab)
		for {
			if !(p != 0) {
				break
			}
			**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
			_sqlite3FkLocateIndex(tls, pParse, pTab, p, bp, uintptr(0))
			if **(**uintptr)(__ccgo_up(bp)) != 0 {
				i = 0
				for {
					if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FnKeyCol)) {
						break
					}
					if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaiColumn + uintptr(i)*2))) > int32(31) {
						v3 = uint32(0xffffffff)
					} else {
						v3 = libc.Uint32FromInt32(1) << **(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).FaiColumn + uintptr(i)*2))
					}
					mask = mask | v3
					goto _5
				_5:
					;
					i = i + 1
				}
			}
			goto _4
		_4:
			;
			p = (*TFKey)(unsafe.Pointer(p)).FpNextTo
		}
	}
	return mask
}

// C documentation
//
//	/*
//	** This function is called before generating code to update or delete a
//	** row contained in table pTab. If the operation is a DELETE, then
//	** parameter aChange is passed a NULL value. For an UPDATE, aChange points
//	** to an array of size N, where N is the number of columns in table pTab.
//	** If the i'th column is not modified by the UPDATE, then the corresponding
//	** entry in the aChange[] array is set to -1. If the column is modified,
//	** the value is 0 or greater. Parameter chngRowid is set to true if the
//	** UPDATE statement modifies the rowid fields of the table.
//	**
//	** If any foreign key processing will be required, this function returns
//	** non-zero. If there is no foreign key related processing, this function
//	** returns zero.
//	**
//	** For an UPDATE, this function returns 2 if:
//	**
//	**   * There are any FKs for which pTab is the child and the parent table
//	**     and any FK processing at all is required (even of a different FK), or
//	**
//	**   * the UPDATE modifies one or more parent keys for which the action is
//	**     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
//	**
//	** Or, assuming some other foreign key processing is required, 1.
//	*/
func _sqlite3FkRequired(tls *libc.TLS, pParse uintptr, pTab uintptr, aChange uintptr, chngRowid int32) (r int32) {
	var bHaveFK, eRet, v3 int32
	var p uintptr
	_, _, _, _ = bHaveFK, eRet, p, v3
	eRet = int32(1) /* Value to return if bHaveFK is true */
	bHaveFK = 0     /* If FK processing is required */
	if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Fflags&uint64(SQLITE_ForeignKeys) != 0 && libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == TABTYP_NORM {
		if !(aChange != 0) {
			/* A DELETE operation. Foreign key processing is required if the
			 ** table in question is either the child or parent table for any
			 ** foreign key constraint.  */
			bHaveFK = libc.BoolInt32(_sqlite3FkReferences(tls, pTab) != 0 || (*(*struct {
				FaddColOffset int32
				FpFKey        uintptr
				FpDfltList    uintptr
			})(unsafe.Pointer(pTab + 44))).FpFKey != 0)
		} else {
			/* Check if any child key columns are being modified. */
			p = (*(*struct {
				FaddColOffset int32
				FpFKey        uintptr
				FpDfltList    uintptr
			})(unsafe.Pointer(pTab + 44))).FpFKey
			for {
				if !(p != 0) {
					break
				}
				if _fkChildIsModified(tls, pTab, p, aChange, chngRowid) != 0 {
					if 0 == Xsqlite3_stricmp(tls, (*TTable)(unsafe.Pointer(pTab)).FzName, (*TFKey)(unsafe.Pointer(p)).FzTo) {
						eRet = int32(2)
					}
					bHaveFK = int32(1)
				}
				goto _1
			_1:
				;
				p = (*TFKey)(unsafe.Pointer(p)).FpNextFrom
			}
			/* Check if any parent key columns are being modified. */
			p = _sqlite3FkReferences(tls, pTab)
			for {
				if !(p != 0) {
					break
				}
				if _fkParentIsModified(tls, pTab, p, aChange, chngRowid) != 0 {
					if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Fflags&(libc.Uint64FromInt32(libc.Int32FromInt32(0x00008))<<libc.Int32FromInt32(32)) == uint64(0) && libc.Int32FromUint8(**(**Tu8)(__ccgo_up(p + 25 + 1))) != OE_None {
						return int32(2)
					}
					bHaveFK = int32(1)
				}
				goto _2
			_2:
				;
				p = (*TFKey)(unsafe.Pointer(p)).FpNextTo
			}
		}
	}
	if bHaveFK != 0 {
		v3 = eRet
	} else {
		v3 = 0
	}
	return v3
}

// C documentation
//
//	/*
//	** Return an IEEE754 floating point value that approximates d*pow(10,p).
//	**
//	** The (current) algorithm is adapted from the work of Ross Cox at
//	** https://github.com/rsc/fpfmt
//	*/
func _sqlite3Fp10Convert2(tls *libc.TLS, d Tu64, p int32) (r float64) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var adj, b, e, lp, s int32
	var hi, pwr10h, sticky, u, x Tu64
	var mid1, mid2 Tu32
	var _ /* lo at bp+8 */ Tu64
	var _ /* m at bp+16 */ Tu64
	var _ /* pwr10l at bp+0 */ Tu32
	var _ /* r at bp+24 */ float64
	_, _, _, _, _, _, _, _, _, _, _, _ = adj, b, e, hi, lp, mid1, mid2, pwr10h, s, sticky, u, x
	if p < -int32(348) {
		return float64(0)
	}
	if p > +libc.Int32FromInt32(347) {
		return float64(libc.X__builtin_inff(tls))
	}
	b = int32(64) - _countLeadingZeros(tls, d)
	lp = _pwr10to2(tls, p)
	e = int32(53) - b - lp
	if e > int32(1074) {
		if e >= int32(1130) {
			return float64(0)
		}
		e = int32(1074)
	}
	s = -(e - (int32(64) - b) + lp + int32(3))
	pwr10h = _powerOfTen(tls, p, bp)
	if **(**Tu32)(__ccgo_up(bp)) != uint32(0) {
		pwr10h = pwr10h + 1
		**(**Tu32)(__ccgo_up(bp)) = ^**(**Tu32)(__ccgo_up(bp))
	}
	x = d << (int32(64) - b)
	hi = _sqlite3Multiply128(tls, x, pwr10h, bp+8)
	mid1 = uint32(**(**Tu64)(__ccgo_up(bp + 8)) >> int32(32))
	sticky = uint64(1)
	if hi&(libc.Uint64FromInt32(1)<<s-uint64(1)) == uint64(0) {
		mid2 = uint32(_sqlite3Multiply128(tls, x, uint64(**(**Tu32)(__ccgo_up(bp)))<<int32(32), bp+8) >> int32(32))
		sticky = libc.BoolUint64(mid1-mid2 > libc.Uint32FromInt32(1))
		hi = hi - libc.BoolUint64(mid1 < mid2)
	}
	u = hi>>s | sticky
	adj = libc.BoolInt32(u >= libc.Uint64FromInt32(1)<<libc.Int32FromInt32(55)-libc.Uint64FromInt32(2))
	if adj != 0 {
		u = u>>adj | u&uint64(1)
		e = e - adj
	}
	**(**Tu64)(__ccgo_up(bp + 16)) = (u + uint64(1) + u>>libc.Int32FromInt32(2)&uint64(1)) >> int32(2)
	if e <= -int32(972) {
		return float64(libc.X__builtin_inff(tls))
	}
	if **(**Tu64)(__ccgo_up(bp + 16))&(libc.Uint64FromInt32(1)<<libc.Int32FromInt32(52)) != uint64(0) {
		**(**Tu64)(__ccgo_up(bp + 16)) = **(**Tu64)(__ccgo_up(bp + 16)) & ^(libc.Uint64FromInt32(1)<<libc.Int32FromInt32(52)) | libc.Uint64FromInt32(libc.Int32FromInt32(1075)-e)<<libc.Int32FromInt32(52)
	}
	libc.Xmemcpy(tls, bp+24, bp+16, uint32(8))
	return **(**float64)(__ccgo_up(bp + 24))
}

// C documentation
//
//	/*
//	** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
//	** the error code in p. If an error has already occurred when this function
//	** is called, it is a no-op.
//	*/
func _sqlite3Fts5BufferAppendBlob(tls *libc.TLS, pRc uintptr, pBuf uintptr, nData Tu32, pData uintptr) {
	var v1 int32
	var v2 uintptr
	_, _ = v1, v2
	if nData != 0 {
		if libc.Uint32FromInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn)+nData <= libc.Uint32FromInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).FnSpace) {
			v1 = 0
		} else {
			v1 = _sqlite3Fts5BufferSize(tls, pRc, pBuf, nData+libc.Uint32FromInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn))
		}
		if v1 != 0 {
			return
		}
		libc.Xmemcpy(tls, (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn), pData, nData)
		v2 = pBuf + 4
		*(*int32)(unsafe.Pointer(v2)) = int32(uint32(*(*int32)(unsafe.Pointer(v2))) + nData)
	}
}

// C documentation
//
//	/*
//	** Append the nul-terminated string zStr to the buffer pBuf. This function
//	** ensures that the byte following the buffer data is set to 0x00, even
//	** though this byte is not included in the pBuf->n count.
//	*/
func _sqlite3Fts5BufferAppendString(tls *libc.TLS, pRc uintptr, pBuf uintptr, zStr uintptr) {
	var nStr int32
	_ = nStr
	nStr = libc.Int32FromUint32(libc.Xstrlen(tls, zStr))
	_sqlite3Fts5BufferAppendBlob(tls, pRc, pBuf, libc.Uint32FromInt32(nStr+int32(1)), zStr)
	(*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn = (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn - 1
}

// C documentation
//
//	/*
//	** Encode value iVal as an SQLite varint and append it to the buffer object
//	** pBuf. If an OOM error occurs, set the error code in p.
//	*/
func _sqlite3Fts5BufferAppendVarint(tls *libc.TLS, pRc uintptr, pBuf uintptr, iVal Ti64) {
	var v1 int32
	_ = v1
	if libc.Uint32FromInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn)+libc.Uint32FromInt32(libc.Int32FromInt32(9)) <= libc.Uint32FromInt32((*TFts5Buffer)(unsafe.Pointer(pBuf)).FnSpace) {
		v1 = 0
	} else {
		v1 = _sqlite3Fts5BufferSize(tls, pRc, pBuf, libc.Uint32FromInt32(int32(9)+(*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn))
	}
	if v1 != 0 {
		return
	}
	**(**int32)(__ccgo_up(pBuf + 4)) += _sqlite3Fts5PutVarint(tls, (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn), libc.Uint64FromInt64(iVal))
}

func _sqlite3Fts5ExprAnd(tls *libc.TLS, pp1 uintptr, p2 uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var ap, p1 uintptr
	var i, nPhrase int32
	var _ /* sParse at bp+0 */ TFts5Parse
	_, _, _, _ = ap, i, nPhrase, p1
	libc.Xmemset(tls, bp, 0, uint32(28))
	if **(**uintptr)(__ccgo_up(pp1)) != 0 && p2 != 0 {
		p1 = **(**uintptr)(__ccgo_up(pp1))
		nPhrase = (*TFts5Expr)(unsafe.Pointer(p1)).FnPhrase + (*TFts5Expr)(unsafe.Pointer(p2)).FnPhrase
		(*TFts5Expr)(unsafe.Pointer(p1)).FpRoot = _sqlite3Fts5ParseNode(tls, bp, int32(FTS5_AND), (*TFts5Expr)(unsafe.Pointer(p1)).FpRoot, (*TFts5Expr)(unsafe.Pointer(p2)).FpRoot, uintptr(0))
		(*TFts5Expr)(unsafe.Pointer(p2)).FpRoot = uintptr(0)
		if (**(**TFts5Parse)(__ccgo_up(bp))).Frc == SQLITE_OK {
			ap = Xsqlite3_realloc64(tls, (*TFts5Expr)(unsafe.Pointer(p1)).FapExprPhrase, uint64(libc.Uint32FromInt32(nPhrase)*uint32(4)))
			if ap == uintptr(0) {
				(**(**TFts5Parse)(__ccgo_up(bp))).Frc = int32(SQLITE_NOMEM)
			} else {
				libc.Xmemmove(tls, ap+uintptr((*TFts5Expr)(unsafe.Pointer(p2)).FnPhrase)*4, ap, libc.Uint32FromInt32((*TFts5Expr)(unsafe.Pointer(p1)).FnPhrase)*uint32(4))
				i = 0
				for {
					if !(i < (*TFts5Expr)(unsafe.Pointer(p2)).FnPhrase) {
						break
					}
					**(**uintptr)(__ccgo_up(ap + uintptr(i)*4)) = **(**uintptr)(__ccgo_up((*TFts5Expr)(unsafe.Pointer(p2)).FapExprPhrase + uintptr(i)*4))
					goto _1
				_1:
					;
					i = i + 1
				}
				(*TFts5Expr)(unsafe.Pointer(p1)).FnPhrase = nPhrase
				(*TFts5Expr)(unsafe.Pointer(p1)).FapExprPhrase = ap
			}
		}
		Xsqlite3_free(tls, (*TFts5Expr)(unsafe.Pointer(p2)).FapExprPhrase)
		Xsqlite3_free(tls, p2)
	} else {
		if p2 != 0 {
			**(**uintptr)(__ccgo_up(pp1)) = p2
		}
	}
	return (**(**TFts5Parse)(__ccgo_up(bp))).Frc
}

// C documentation
//
//	/*
//	** Clear the position lists associated with all phrases in the expression
//	** passed as the first argument. Argument bLive is true if the expression
//	** might be pointing to a real entry, otherwise it has just been reset.
//	**
//	** At present this function is only used for detail=col and detail=none
//	** fts5 tables. This implies that all phrases must be at most 1 token
//	** in size, as phrase matches are not supported without detail=full.
//	*/
func _sqlite3Fts5ExprClearPoslists(tls *libc.TLS, pExpr uintptr, bLive int32) (r uintptr) {
	var i int32
	var pBuf, pNode, pRet uintptr
	_, _, _, _ = i, pBuf, pNode, pRet
	pRet = Xsqlite3_malloc64(tls, uint64(uint32(16)*libc.Uint32FromInt32((*TFts5Expr)(unsafe.Pointer(pExpr)).FnPhrase)))
	if pRet != 0 {
		libc.Xmemset(tls, pRet, 0, uint32(16)*libc.Uint32FromInt32((*TFts5Expr)(unsafe.Pointer(pExpr)).FnPhrase))
		i = 0
		for {
			if !(i < (*TFts5Expr)(unsafe.Pointer(pExpr)).FnPhrase) {
				break
			}
			pBuf = **(**uintptr)(__ccgo_up((*TFts5Expr)(unsafe.Pointer(pExpr)).FapExprPhrase + uintptr(i)*4)) + 4
			pNode = (*TFts5ExprPhrase)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TFts5Expr)(unsafe.Pointer(pExpr)).FapExprPhrase + uintptr(i)*4)))).FpNode
			if bLive != 0 && ((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn == 0 || (*TFts5ExprNode)(unsafe.Pointer(pNode)).FiRowid != (*TFts5ExprNode)(unsafe.Pointer((*TFts5Expr)(unsafe.Pointer(pExpr)).FpRoot)).FiRowid || (*TFts5ExprNode)(unsafe.Pointer(pNode)).FbEof != 0) {
				(**(**TFts5PoslistPopulator)(__ccgo_up(pRet + uintptr(i)*16))).FbMiss = int32(1)
			} else {
				(*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn = 0
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	return pRet
}

func _sqlite3Fts5ExprNew(tls *libc.TLS, pConfig uintptr, bPhraseToAnd int32, iCol int32, zExpr uintptr, ppNew uintptr, pzErr uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var n, t int32
	var pColset, pEngine, pNew, v1 uintptr
	var _ /* sParse at bp+0 */ TFts5Parse
	var _ /* token at bp+32 */ TFts5Token
	var _ /* z at bp+40 */ uintptr
	_, _, _, _, _, _ = n, pColset, pEngine, pNew, t, v1
	**(**uintptr)(__ccgo_up(bp + 40)) = zExpr
	**(**uintptr)(__ccgo_up(ppNew)) = uintptr(0)
	**(**uintptr)(__ccgo_up(pzErr)) = uintptr(0)
	libc.Xmemset(tls, bp, 0, uint32(28))
	(**(**TFts5Parse)(__ccgo_up(bp))).FbPhraseToAnd = bPhraseToAnd
	pEngine = _sqlite3Fts5ParserAlloc(tls, __ccgo_fp(_fts5ParseAlloc))
	if pEngine == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	(**(**TFts5Parse)(__ccgo_up(bp))).FpConfig = pConfig
	for cond := true; cond; cond = (**(**TFts5Parse)(__ccgo_up(bp))).Frc == SQLITE_OK && t != FTS5_EOF {
		t = _fts5ExprGetToken(tls, bp, bp+40, bp+32)
		_sqlite3Fts5Parser(tls, pEngine, t, **(**TFts5Token)(__ccgo_up(bp + 32)), bp)
	}
	_sqlite3Fts5ParserFree(tls, pEngine, __ccgo_fp(_fts5ParseFree))
	/* If the LHS of the MATCH expression was a user column, apply the
	 ** implicit column-filter.  */
	if (**(**TFts5Parse)(__ccgo_up(bp))).Frc == SQLITE_OK && iCol < (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol {
		n = libc.Int32FromUint32(libc.Uint32FromInt64(8) * libc.Uint32FromInt32((libc.Int32FromInt32(1)+libc.Int32FromInt32(2))/libc.Int32FromInt32(2)))
		pColset = _sqlite3Fts5MallocZero(tls, bp+8, int64(n))
		if pColset != 0 {
			(*TFts5Colset)(unsafe.Pointer(pColset)).FnCol = int32(1)
			*(*int32)(unsafe.Pointer(pColset + 4)) = iCol
			_sqlite3Fts5ParseSetColset(tls, bp, (**(**TFts5Parse)(__ccgo_up(bp))).FpExpr, pColset)
		}
	}
	if (**(**TFts5Parse)(__ccgo_up(bp))).Frc == SQLITE_OK {
		v1 = Xsqlite3_malloc64(tls, uint64(24))
		pNew = v1
		**(**uintptr)(__ccgo_up(ppNew)) = v1
		if pNew == uintptr(0) {
			(**(**TFts5Parse)(__ccgo_up(bp))).Frc = int32(SQLITE_NOMEM)
			_sqlite3Fts5ParseNodeFree(tls, (**(**TFts5Parse)(__ccgo_up(bp))).FpExpr)
		} else {
			(*TFts5Expr)(unsafe.Pointer(pNew)).FpRoot = (**(**TFts5Parse)(__ccgo_up(bp))).FpExpr
			(*TFts5Expr)(unsafe.Pointer(pNew)).FpIndex = uintptr(0)
			(*TFts5Expr)(unsafe.Pointer(pNew)).FpConfig = pConfig
			(*TFts5Expr)(unsafe.Pointer(pNew)).FapExprPhrase = (**(**TFts5Parse)(__ccgo_up(bp))).FapPhrase
			(*TFts5Expr)(unsafe.Pointer(pNew)).FnPhrase = (**(**TFts5Parse)(__ccgo_up(bp))).FnPhrase
			(*TFts5Expr)(unsafe.Pointer(pNew)).FbDesc = 0
			(**(**TFts5Parse)(__ccgo_up(bp))).FapPhrase = uintptr(0)
		}
	} else {
		_sqlite3Fts5ParseNodeFree(tls, (**(**TFts5Parse)(__ccgo_up(bp))).FpExpr)
	}
	Xsqlite3_free(tls, (**(**TFts5Parse)(__ccgo_up(bp))).FapPhrase)
	if uintptr(0) == **(**uintptr)(__ccgo_up(pzErr)) {
		**(**uintptr)(__ccgo_up(pzErr)) = (**(**TFts5Parse)(__ccgo_up(bp))).FzErr
	} else {
		Xsqlite3_free(tls, (**(**TFts5Parse)(__ccgo_up(bp))).FzErr)
	}
	return (**(**TFts5Parse)(__ccgo_up(bp))).Frc
}

// C documentation
//
//	/*
//	** Empty (but do not delete) a hash table.
//	*/
func _sqlite3Fts5HashClear(tls *libc.TLS, pHash uintptr) {
	var i int32
	var pNext, pSlot uintptr
	_, _, _ = i, pNext, pSlot
	i = 0
	for {
		if !(i < (*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot) {
			break
		}
		pSlot = **(**uintptr)(__ccgo_up((*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot + uintptr(i)*4))
		for {
			if !(pSlot != 0) {
				break
			}
			pNext = (*TFts5HashEntry)(unsafe.Pointer(pSlot)).FpHashNext
			Xsqlite3_free(tls, pSlot)
			goto _2
		_2:
			;
			pSlot = pNext
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	libc.Xmemset(tls, (*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot, 0, libc.Uint32FromInt32((*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot)*uint32(4))
	(*TFts5Hash)(unsafe.Pointer(pHash)).FnEntry = 0
}

// C documentation
//
//	/*
//	** Allocate a new hash table.
//	*/
func _sqlite3Fts5HashNew(tls *libc.TLS, pConfig uintptr, ppNew uintptr, pnByte uintptr) (r int32) {
	var nByte Tsqlite3_int64
	var pNew, v1 uintptr
	var rc int32
	_, _, _, _ = nByte, pNew, rc, v1
	rc = SQLITE_OK
	v1 = Xsqlite3_malloc64(tls, uint64(24))
	pNew = v1
	**(**uintptr)(__ccgo_up(ppNew)) = v1
	if pNew == uintptr(0) {
		rc = int32(SQLITE_NOMEM)
	} else {
		libc.Xmemset(tls, pNew, 0, uint32(24))
		(*TFts5Hash)(unsafe.Pointer(pNew)).FpnByte = pnByte
		(*TFts5Hash)(unsafe.Pointer(pNew)).FeDetail = (*TFts5Config)(unsafe.Pointer(pConfig)).FeDetail
		(*TFts5Hash)(unsafe.Pointer(pNew)).FnSlot = int32(1024)
		nByte = libc.Int64FromUint32(uint32(4) * libc.Uint32FromInt32((*TFts5Hash)(unsafe.Pointer(pNew)).FnSlot))
		(*TFts5Hash)(unsafe.Pointer(pNew)).FaSlot = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if (*TFts5Hash)(unsafe.Pointer(pNew)).FaSlot == uintptr(0) {
			Xsqlite3_free(tls, pNew)
			**(**uintptr)(__ccgo_up(ppNew)) = uintptr(0)
			rc = int32(SQLITE_NOMEM)
		} else {
			libc.Xmemset(tls, (*TFts5Hash)(unsafe.Pointer(pNew)).FaSlot, 0, libc.Uint32FromInt64(nByte))
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Query the hash table for a doclist associated with term pTerm/nTerm.
//	*/
func _sqlite3Fts5HashQuery(tls *libc.TLS, pHash uintptr, nPre int32, pTerm uintptr, nTerm int32, ppOut uintptr, pnDoclist uintptr) (r int32) {
	var iHash uint32
	var nHashPre, nList int32
	var p, pFaux, pRet, zKey, v2 uintptr
	_, _, _, _, _, _, _, _ = iHash, nHashPre, nList, p, pFaux, pRet, zKey, v2
	iHash = _fts5HashKey(tls, (*TFts5Hash)(unsafe.Pointer(pHash)).FnSlot, pTerm, nTerm)
	zKey = uintptr(0)
	p = **(**uintptr)(__ccgo_up((*TFts5Hash)(unsafe.Pointer(pHash)).FaSlot + uintptr(iHash)*4))
	for {
		if !(p != 0) {
			break
		}
		zKey = p + 1*40
		if nTerm == (*TFts5HashEntry)(unsafe.Pointer(p)).FnKey && libc.Xmemcmp(tls, zKey, pTerm, libc.Uint32FromInt32(nTerm)) == 0 {
			break
		}
		goto _1
	_1:
		;
		p = (*TFts5HashEntry)(unsafe.Pointer(p)).FpHashNext
	}
	if p != 0 {
		nHashPre = libc.Int32FromUint32(uint32(40) + libc.Uint32FromInt32(nTerm))
		nList = (*TFts5HashEntry)(unsafe.Pointer(p)).FnData - nHashPre
		v2 = Xsqlite3_malloc64(tls, libc.Uint64FromInt32(nPre+nList+int32(10)))
		**(**uintptr)(__ccgo_up(ppOut)) = v2
		pRet = v2
		if pRet != 0 {
			pFaux = pRet + uintptr(nPre-nHashPre)
			libc.Xmemcpy(tls, pRet+uintptr(nPre), p+uintptr(nHashPre), libc.Uint32FromInt32(nList))
			nList = nList + _fts5HashAddPoslistSize(tls, pHash, p, pFaux)
			**(**int32)(__ccgo_up(pnDoclist)) = nList
		} else {
			**(**int32)(__ccgo_up(pnDoclist)) = 0
			return int32(SQLITE_NOMEM)
		}
	} else {
		**(**uintptr)(__ccgo_up(ppOut)) = uintptr(0)
		**(**int32)(__ccgo_up(pnDoclist)) = 0
	}
	return SQLITE_OK
}

func _sqlite3Fts5HashScanEntry(tls *libc.TLS, pHash uintptr, pzTerm uintptr, pnTerm uintptr, ppDoclist uintptr, pnDoclist uintptr) {
	var nTerm int32
	var p, zKey, v1 uintptr
	_, _, _, _ = nTerm, p, zKey, v1
	v1 = (*TFts5Hash)(unsafe.Pointer(pHash)).FpScan
	p = v1
	if v1 != 0 {
		zKey = p + 1*40
		nTerm = (*TFts5HashEntry)(unsafe.Pointer(p)).FnKey
		_fts5HashAddPoslistSize(tls, pHash, p, uintptr(0))
		**(**uintptr)(__ccgo_up(pzTerm)) = zKey
		**(**int32)(__ccgo_up(pnTerm)) = nTerm
		**(**uintptr)(__ccgo_up(ppDoclist)) = zKey + uintptr(nTerm)
		**(**int32)(__ccgo_up(pnDoclist)) = libc.Int32FromUint32(libc.Uint32FromInt32((*TFts5HashEntry)(unsafe.Pointer(p)).FnData) - (uint32(40) + libc.Uint32FromInt32(nTerm)))
	} else {
		**(**uintptr)(__ccgo_up(pzTerm)) = uintptr(0)
		**(**int32)(__ccgo_up(pnTerm)) = 0
		**(**uintptr)(__ccgo_up(ppDoclist)) = uintptr(0)
		**(**int32)(__ccgo_up(pnDoclist)) = 0
	}
}

/*
** 2014 May 31
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** Low level access to the FTS index stored in the database file. The
** routines in this file file implement all read and write access to the
** %_data table. Other parts of the system access this functionality via
** the interface defined in fts5Int.h.
 */

/* #include "fts5Int.h" */

/*
** Overview:
**
** The %_data table contains all the FTS indexes for an FTS5 virtual table.
** As well as the main term index, there may be up to 31 prefix indexes.
** The format is similar to FTS3/4, except that:
**
**   * all segment b-tree leaf data is stored in fixed size page records
**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
**     taken to ensure it is possible to iterate in either direction through
**     the entries in a doclist, or to seek to a specific entry within a
**     doclist, without loading it into memory.
**
**   * large doclists that span many pages have associated "doclist index"
**     records that contain a copy of the first rowid on each page spanned by
**     the doclist. This is used to speed up seek operations, and merges of
**     large doclists with very small doclists.
**
**   * extra fields in the "structure record" record the state of ongoing
**     incremental merge operations.
**
 */

/*
** There are two versions of the format used for the structure record:
**
**   1. the legacy format, that may be read by all fts5 versions, and
**
**   2. the V2 format, which is used by contentless_delete=1 databases.
**
** Both begin with a 4-byte "configuration cookie" value. Then, a legacy
** format structure record contains a varint - the number of levels in
** the structure. Whereas a V2 structure record contains the constant
** 4 bytes [0xff 0x00 0x00 0x01]. This is unambiguous as the value of a
** varint has to be at least 16256 to begin with "0xFF". And the default
** maximum number of levels is 64.
**
** See below for more on structure record formats.
 */

/*
** Details:
**
** The %_data table managed by this module,
**
**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
**
** , contains the following 6 types of records. See the comments surrounding
** the FTS5_*_ROWID macros below for a description of how %_data rowids are
** assigned to each fo them.
**
** 1. Structure Records:
**
**   The set of segments that make up an index - the index structure - are
**   recorded in a single record within the %_data table. The record consists
**   of a single 32-bit configuration cookie value followed by a list of
**   SQLite varints.
**
**   If the structure record is a V2 record, the configuration cookie is
**   followed by the following 4 bytes: [0xFF 0x00 0x00 0x01].
**
**   Next, the record continues with three varints:
**
**     + number of levels,
**     + total number of segments on all levels,
**     + value of write counter.
**
**   Then, for each level from 0 to nMax:
**
**     + number of input segments in ongoing merge.
**     + total number of segments in level.
**     + for each segment from oldest to newest:
**         + segment id (always > 0)
**         + first leaf page number (often 1, always greater than 0)
**         + final leaf page number
**
**      Then, for V2 structures only:
**
**         + lower origin counter value,
**         + upper origin counter value,
**         + the number of tombstone hash pages.
**
** 2. The Averages Record:
**
**   A single record within the %_data table. The data is a list of varints.
**   The first value is the number of rows in the index. Then, for each column
**   from left to right, the total number of tokens in the column for all
**   rows of the table.
**
** 3. Segment leaves:
**
**   TERM/DOCLIST FORMAT:
**
**     Most of each segment leaf is taken up by term/doclist data. The
**     general format of term/doclist, starting with the first term
**     on the leaf page, is:
**
**         varint : size of first term
**         blob:    first term data
**         doclist: first doclist
**         zero-or-more {
**           varint:  number of bytes in common with previous term
**           varint:  number of bytes of new term data (nNew)
**           blob:    nNew bytes of new term data
**           doclist: next doclist
**         }
**
**     doclist format:
**
**         varint:  first rowid
**         poslist: first poslist
**         zero-or-more {
**           varint:  rowid delta (always > 0)
**           poslist: next poslist
**         }
**
**     poslist format:
**
**         varint: size of poslist in bytes multiplied by 2, not including
**                 this field. Plus 1 if this entry carries the "delete" flag.
**         collist: collist for column 0
**         zero-or-more {
**           0x01 byte
**           varint: column number (I)
**           collist: collist for column I
**         }
**
**     collist format:
**
**         varint: first offset + 2
**         zero-or-more {
**           varint: offset delta + 2
**         }
**
**   PAGE FORMAT
**
**     Each leaf page begins with a 4-byte header containing 2 16-bit
**     unsigned integer fields in big-endian format. They are:
**
**       * The byte offset of the first rowid on the page, if it exists
**         and occurs before the first term (otherwise 0).
**
**       * The byte offset of the start of the page footer. If the page
**         footer is 0 bytes in size, then this field is the same as the
**         size of the leaf page in bytes.
**
**     The page footer consists of a single varint for each term located
**     on the page. Each varint is the byte offset of the current term
**     within the page, delta-compressed against the previous value. In
**     other words, the first varint in the footer is the byte offset of
**     the first term, the second is the byte offset of the second less that
**     of the first, and so on.
**
**     The term/doclist format described above is accurate if the entire
**     term/doclist data fits on a single leaf page. If this is not the case,
**     the format is changed in two ways:
**
**       + if the first rowid on a page occurs before the first term, it
**         is stored as a literal value:
**
**             varint:  first rowid
**
**       + the first term on each page is stored in the same way as the
**         very first term of the segment:
**
**             varint : size of first term
**             blob:    first term data
**
** 5. Segment doclist indexes:
**
**   Doclist indexes are themselves b-trees, however they usually consist of
**   a single leaf record only. The format of each doclist index leaf page
**   is:
**
**     * Flags byte. Bits are:
**         0x01: Clear if leaf is also the root page, otherwise set.
**
**     * Page number of fts index leaf page. As a varint.
**
**     * First rowid on page indicated by previous field. As a varint.
**
**     * A list of varints, one for each subsequent termless page. A
**       positive delta if the termless page contains at least one rowid,
**       or an 0x00 byte otherwise.
**
**   Internal doclist index nodes are:
**
**     * Flags byte. Bits are:
**         0x01: Clear for root page, otherwise set.
**
**     * Page number of first child page. As a varint.
**
**     * Copy of first rowid on page indicated by previous field. As a varint.
**
**     * A list of delta-encoded varints - the first rowid on each subsequent
**       child page.
**
** 6. Tombstone Hash Page
**
**   These records are only ever present in contentless_delete=1 tables.
**   There are zero or more of these associated with each segment. They
**   are used to store the tombstone rowids for rows contained in the
**   associated segments.
**
**   The set of nHashPg tombstone hash pages associated with a single
**   segment together form a single hash table containing tombstone rowids.
**   To find the page of the hash on which a key might be stored:
**
**       iPg = (rowid % nHashPg)
**
**   Then, within page iPg, which has nSlot slots:
**
**       iSlot = (rowid / nHashPg) % nSlot
**
**   Each tombstone hash page begins with an 8 byte header:
**
**     1-byte:  Key-size (the size in bytes of each slot). Either 4 or 8.
**     1-byte:  rowid-0-tombstone flag. This flag is only valid on the
**              first tombstone hash page for each segment (iPg=0). If set,
**              the hash table contains rowid 0. If clear, it does not.
**              Rowid 0 is handled specially.
**     2-bytes: unused.
**     4-bytes: Big-endian integer containing number of entries on page.
**
**   Following this are nSlot 4 or 8 byte slots (depending on the key-size
**   in the first byte of the page header). The number of slots may be
**   determined based on the size of the page record and the key-size:
**
**     nSlot = (nByte - 8) / key-size
 */

/*
** Rowids for the averages and structure records in the %_data table.
 */

/*
** Macros determining the rowids used by segment leaves and dlidx leaves
** and nodes. All nodes and leaves are stored in the %_data table with large
** positive rowids.
**
** Each segment has a unique non-zero 16-bit id.
**
** The rowid for each segment leaf is found by passing the segment id and
** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
** sequentially starting from 1.
 */

/*
** Each time a blob is read from the %_data table, it is padded with this
** many zero bytes. This makes it easier to decode the various record formats
** without overreading if the records are corrupt.
 */

// C documentation
//
//	/*
//	** Read and decode the "averages" record from the database.
//	**
//	** Parameter anSize must point to an array of size nCol, where nCol is
//	** the number of user defined columns in the FTS table.
//	*/
func _sqlite3Fts5IndexGetAverages(tls *libc.TLS, p uintptr, pnRow uintptr, anSize uintptr) (r int32) {
	var i, iCol, nCol int32
	var pData uintptr
	_, _, _, _ = i, iCol, nCol, pData
	nCol = (*TFts5Config)(unsafe.Pointer((*TFts5Index)(unsafe.Pointer(p)).FpConfig)).FnCol
	**(**Ti64)(__ccgo_up(pnRow)) = 0
	libc.Xmemset(tls, anSize, 0, uint32(8)*libc.Uint32FromInt32(nCol))
	pData = _fts5DataRead(tls, p, int64(FTS5_AVERAGES_ROWID))
	if (*TFts5Index)(unsafe.Pointer(p)).Frc == SQLITE_OK && (*TFts5Data)(unsafe.Pointer(pData)).Fnn != 0 {
		i = 0
		i = i + libc.Int32FromUint8(_sqlite3Fts5GetVarint(tls, (*TFts5Data)(unsafe.Pointer(pData)).Fp+uintptr(i), pnRow))
		iCol = 0
		for {
			if !(i < (*TFts5Data)(unsafe.Pointer(pData)).Fnn && iCol < nCol) {
				break
			}
			i = i + libc.Int32FromUint8(_sqlite3Fts5GetVarint(tls, (*TFts5Data)(unsafe.Pointer(pData)).Fp+uintptr(i), anSize+uintptr(iCol)*8))
			goto _1
		_1:
			;
			iCol = iCol + 1
		}
	}
	_fts5DataRelease(tls, pData)
	return _fts5IndexReturn(tls, p)
}

func _sqlite3Fts5MallocZero(tls *libc.TLS, pRc uintptr, nByte Tsqlite3_int64) (r uintptr) {
	var pRet uintptr
	_ = pRet
	pRet = uintptr(0)
	if **(**int32)(__ccgo_up(pRc)) == SQLITE_OK {
		pRet = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
		if pRet == uintptr(0) {
			if nByte > 0 {
				**(**int32)(__ccgo_up(pRc)) = int32(SQLITE_NOMEM)
			}
		} else {
			libc.Xmemset(tls, pRet, 0, libc.Uint32FromInt64(nByte))
		}
	}
	return pRet
}

// C documentation
//
//	/*
//	** Allocate and return an Fts5Colset object specifying the inverse of
//	** the colset passed as the second argument. Free the colset passed
//	** as the second argument before returning.
//	*/
func _sqlite3Fts5ParseColsetInvert(tls *libc.TLS, pParse uintptr, p uintptr) (r uintptr) {
	var i, iOld, nCol, v2 int32
	var pRet, v3 uintptr
	_, _, _, _, _, _ = i, iOld, nCol, pRet, v2, v3
	nCol = (*TFts5Config)(unsafe.Pointer((*TFts5Parse)(unsafe.Pointer(pParse)).FpConfig)).FnCol
	pRet = _sqlite3Fts5MallocZero(tls, pParse+8, libc.Int64FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32((nCol+libc.Int32FromInt32(1)+libc.Int32FromInt32(2))/libc.Int32FromInt32(2))))
	if pRet != 0 {
		iOld = 0
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			if iOld >= (*TFts5Colset)(unsafe.Pointer(p)).FnCol || *(*int32)(unsafe.Pointer(p + 4 + uintptr(iOld)*4)) != i {
				v3 = pRet
				v2 = *(*int32)(unsafe.Pointer(v3))
				*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
				*(*int32)(unsafe.Pointer(pRet + 4 + uintptr(v2)*4)) = i
			} else {
				iOld = iOld + 1
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	Xsqlite3_free(tls, p)
	return pRet
}

// C documentation
//
//	/*
//	** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
//	** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
//	** appended to it and the results returned.
//	**
//	** If an OOM error occurs, both the pNear and pPhrase objects are freed and
//	** NULL returned.
//	*/
func _sqlite3Fts5ParseNearset(tls *libc.TLS, pParse uintptr, pNear uintptr, pPhrase uintptr) (r uintptr) {
	var SZALLOC, nNew, v1 int32
	var nByte, nByte1 Tsqlite3_int64
	var pLast, pRet, v2 uintptr
	_, _, _, _, _, _, _, _ = SZALLOC, nByte, nByte1, nNew, pLast, pRet, v1, v2
	SZALLOC = int32(8)
	pRet = uintptr(0)
	if (*TFts5Parse)(unsafe.Pointer(pParse)).Frc == SQLITE_OK {
		if pNear == uintptr(0) {
			nByte = libc.Int64FromUint32(uint32(libc.UintptrFromInt32(0)+12) + libc.Uint32FromInt32(SZALLOC+libc.Int32FromInt32(1))*libc.Uint32FromInt64(4))
			pRet = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte))
			if pRet == uintptr(0) {
				(*TFts5Parse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
			} else {
				libc.Xmemset(tls, pRet, 0, libc.Uint32FromInt64(nByte))
			}
		} else {
			if (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase%SZALLOC == 0 {
				nNew = (*TFts5ExprNearset)(unsafe.Pointer(pNear)).FnPhrase + SZALLOC
				nByte1 = libc.Int64FromUint32(uint32(libc.UintptrFromInt32(0)+12) + libc.Uint32FromInt32(nNew+libc.Int32FromInt32(1))*libc.Uint32FromInt64(4))
				pRet = Xsqlite3_realloc64(tls, pNear, libc.Uint64FromInt64(nByte1))
				if pRet == uintptr(0) {
					(*TFts5Parse)(unsafe.Pointer(pParse)).Frc = int32(SQLITE_NOMEM)
				}
			} else {
				pRet = pNear
			}
		}
	}
	if pRet == uintptr(0) {
		_sqlite3Fts5ParseNearsetFree(tls, pNear)
		_sqlite3Fts5ParsePhraseFree(tls, pPhrase)
	} else {
		if (*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase > 0 {
			pLast = *(*uintptr)(unsafe.Pointer(pRet + 12 + uintptr((*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase-int32(1))*4))
			if (*TFts5ExprPhrase)(unsafe.Pointer(pPhrase)).FnTerm == 0 {
				_fts5ExprPhraseFree(tls, pPhrase)
				(*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase = (*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase - 1
				(*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase = (*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase - 1
				pPhrase = pLast
			} else {
				if (*TFts5ExprPhrase)(unsafe.Pointer(pLast)).FnTerm == 0 {
					_fts5ExprPhraseFree(tls, pLast)
					**(**uintptr)(__ccgo_up((*TFts5Parse)(unsafe.Pointer(pParse)).FapPhrase + uintptr((*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase-int32(2))*4)) = pPhrase
					(*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase = (*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase - 1
					(*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase = (*TFts5ExprNearset)(unsafe.Pointer(pRet)).FnPhrase - 1
				}
			}
		}
		v2 = pRet + 8
		v1 = *(*int32)(unsafe.Pointer(v2))
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		*(*uintptr)(unsafe.Pointer(pRet + 12 + uintptr(v1)*4)) = pPhrase
	}
	return pRet
}

// C documentation
//
//	/*
//	** This function is called by the parser to process a string token. The
//	** string may or may not be quoted. In any case it is tokenized and a
//	** phrase object consisting of all tokens returned.
//	*/
func _sqlite3Fts5ParseTerm(tls *libc.TLS, pParse uintptr, pAppend uintptr, pToken uintptr, bPrefix int32) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var flags, n, rc, v1 int32
	var pConfig uintptr
	var v3 bool
	var _ /* sCtx at bp+0 */ TTokenCtx
	var _ /* z at bp+12 */ uintptr
	_, _, _, _, _, _ = flags, n, pConfig, rc, v1, v3
	pConfig = (*TFts5Parse)(unsafe.Pointer(pParse)).FpConfig /* Tokenize return code */
	**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
	libc.Xmemset(tls, bp, 0, uint32(12))
	(**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase = pAppend
	(**(**TTokenCtx)(__ccgo_up(bp))).FpConfig = pConfig
	rc = _fts5ParseStringFromToken(tls, pToken, bp+12)
	if rc == SQLITE_OK {
		if bPrefix != 0 {
			v1 = int32(FTS5_TOKENIZE_PREFIX)
		} else {
			v1 = 0
		}
		flags = int32(FTS5_TOKENIZE_QUERY) | v1
		_sqlite3Fts5Dequote(tls, **(**uintptr)(__ccgo_up(bp + 12)))
		n = libc.Int32FromUint32(libc.Xstrlen(tls, **(**uintptr)(__ccgo_up(bp + 12))))
		rc = _sqlite3Fts5Tokenize(tls, pConfig, flags, **(**uintptr)(__ccgo_up(bp + 12)), n, bp, __ccgo_fp(_fts5ParseTokenize))
	}
	Xsqlite3_free(tls, **(**uintptr)(__ccgo_up(bp + 12)))
	if v3 = rc != 0; !v3 {
		v1 = (**(**TTokenCtx)(__ccgo_up(bp))).Frc
		rc = v1
	}
	if v3 || v1 != 0 {
		(*TFts5Parse)(unsafe.Pointer(pParse)).Frc = rc
		_fts5ExprPhraseFree(tls, (**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase)
		(**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase = uintptr(0)
	} else {
		if pAppend == uintptr(0) {
			if _parseGrowPhraseArray(tls, pParse) != 0 {
				_fts5ExprPhraseFree(tls, (**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase)
				return uintptr(0)
			}
			(*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase = (*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase + 1
		}
		if (**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase == uintptr(0) {
			/* This happens when parsing a token or quoted phrase that contains
			 ** no token characters at all. (e.g ... MATCH '""'). */
			(**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase = _sqlite3Fts5MallocZero(tls, pParse+8, libc.Int64FromUint32(uint32(libc.UintptrFromInt32(0)+20)+libc.Uint32FromInt32(libc.Int32FromInt32(1))*libc.Uint32FromInt64(24)))
		} else {
			if (*TFts5ExprPhrase)(unsafe.Pointer((**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase)).FnTerm != 0 {
				(*(*TFts5ExprTerm)(unsafe.Pointer((**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase + 20 + uintptr((*TFts5ExprPhrase)(unsafe.Pointer((**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase)).FnTerm-int32(1))*24))).FbPrefix = libc.Uint8FromInt32(bPrefix)
			}
		}
		**(**uintptr)(__ccgo_up((*TFts5Parse)(unsafe.Pointer(pParse)).FapPhrase + uintptr((*TFts5Parse)(unsafe.Pointer(pParse)).FnPhrase-int32(1))*4)) = (**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase
	}
	return (**(**TTokenCtx)(__ccgo_up(bp))).FpPhrase
}

// C documentation
//
//	/* The main parser program.
//	** The first argument is a pointer to a structure obtained from
//	** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
//	** The second argument is the major token number.  The third is
//	** the minor token.  The fourth optional argument is whatever the
//	** user wants (and specified in the grammar) and is available for
//	** use by the action routines.
//	**
//	** Inputs:
//	** <ul>
//	** <li> A pointer to the parser (an opaque structure.)
//	** <li> The major token number.
//	** <li> The minor token number.
//	** <li> An option argument of a grammar-specified type.
//	** </ul>
//	**
//	** Outputs:
//	** None.
//	*/
func _sqlite3Fts5Parser(tls *libc.TLS, fts5yyp uintptr, fts5yymajor int32, fts5yyminor TFts5Token, pParse uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var fts5yyact uint8
	var fts5yypParser uintptr
	var fts5yyruleno uint32
	var _ /* fts5yyminorunion at bp+0 */ Tfts5YYMINORTYPE
	_, _, _ = fts5yyact, fts5yypParser, fts5yyruleno /* The parser action. */
	fts5yypParser = fts5yyp                          /* The parser */
	(*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).FpParse = pParse
	fts5yyact = (*Tfts5yyStackEntry)(unsafe.Pointer((*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos)).Fstateno
	for int32(1) != 0 { /* Exit by "break" */
		fts5yyact = _fts5yy_find_shift_action(tls, libc.Uint8FromInt32(fts5yymajor), fts5yyact)
		if libc.Int32FromUint8(fts5yyact) >= int32(fts5YY_MIN_REDUCE) {
			fts5yyruleno = libc.Uint32FromInt32(libc.Int32FromUint8(fts5yyact) - int32(fts5YY_MIN_REDUCE)) /* Reduce by this rule */
			/* Check that the stack is large enough to grow by a single entry
			 ** if the RHS of the rule is empty.  This ensures that there is room
			 ** enough on the stack to push the LHS value */
			if int32(_fts5yyRuleInfoNRhs[fts5yyruleno]) == 0 {
				if (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos >= (*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yystackEnd {
					if int32(1) != 0 {
						_fts5yyStackOverflow(tls, fts5yypParser)
						break
					}
				}
			}
			fts5yyact = _fts5yy_reduce(tls, fts5yypParser, fts5yyruleno, fts5yymajor, fts5yyminor)
		} else {
			if libc.Int32FromUint8(fts5yyact) <= int32(fts5YY_MAX_SHIFTREDUCE) {
				_fts5yy_shift(tls, fts5yypParser, fts5yyact, libc.Uint8FromInt32(fts5yymajor), fts5yyminor)
				break
			} else {
				if libc.Int32FromUint8(fts5yyact) == int32(fts5YY_ACCEPT_ACTION) {
					(*Tfts5yyParser)(unsafe.Pointer(fts5yypParser)).Ffts5yytos -= 12
					_fts5yy_accept(tls, fts5yypParser)
					return
				} else {
					*(*TFts5Token)(unsafe.Pointer(bp)) = fts5yyminor
					/* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
					 ** do any kind of error recovery.  Instead, simply invoke the syntax
					 ** error routine and continue going as if nothing had happened.
					 **
					 ** Applications can set this macro (for example inside %include) if
					 ** they intend to abandon the parse upon the first syntax error seen.
					 */
					_fts5yy_syntax_error(tls, fts5yypParser, fts5yymajor, fts5yyminor)
					_fts5yy_destructor(tls, fts5yypParser, libc.Uint8FromInt32(fts5yymajor), bp)
					break
				}
			}
		}
	}
	return
}

// C documentation
//
//	/*
//	** Clear all secondary memory allocations from the parser
//	*/
func _sqlite3Fts5ParserFinalize(tls *libc.TLS, p uintptr) {
	var fts5yytos, pParser uintptr
	_, _ = fts5yytos, pParser
	pParser = p
	/* In-lined version of calling fts5yy_pop_parser_stack() for each
	 ** element left in the stack */
	fts5yytos = (*Tfts5yyParser)(unsafe.Pointer(pParser)).Ffts5yytos
	for fts5yytos > (*Tfts5yyParser)(unsafe.Pointer(pParser)).Ffts5yystack {
		if libc.Int32FromUint8((*Tfts5yyStackEntry)(unsafe.Pointer(fts5yytos)).Fmajor) >= int32(fts5YY_MIN_DSTRCTR) {
			_fts5yy_destructor(tls, pParser, (*Tfts5yyStackEntry)(unsafe.Pointer(fts5yytos)).Fmajor, fts5yytos+4)
		}
		fts5yytos -= 12
	}
}

func _sqlite3Fts5PoslistReaderInit(tls *libc.TLS, a uintptr, n int32, pIter uintptr) (r int32) {
	libc.Xmemset(tls, pIter, 0, uint32(24))
	(*TFts5PoslistReader)(unsafe.Pointer(pIter)).Fa = a
	(*TFts5PoslistReader)(unsafe.Pointer(pIter)).Fn = n
	_sqlite3Fts5PoslistReaderNext(tls, pIter)
	return libc.Int32FromUint8((*TFts5PoslistReader)(unsafe.Pointer(pIter)).FbEof)
}

// C documentation
//
//	/*
//	** Advance the iterator object passed as the only argument. Return true
//	** if the iterator reaches EOF, or false otherwise.
//	*/
func _sqlite3Fts5PoslistReaderNext(tls *libc.TLS, pIter uintptr) (r int32) {
	if _sqlite3Fts5PoslistNext64(tls, (*TFts5PoslistReader)(unsafe.Pointer(pIter)).Fa, (*TFts5PoslistReader)(unsafe.Pointer(pIter)).Fn, pIter+8, pIter+16) != 0 {
		(*TFts5PoslistReader)(unsafe.Pointer(pIter)).FbEof = uint8(1)
	}
	return libc.Int32FromUint8((*TFts5PoslistReader)(unsafe.Pointer(pIter)).FbEof)
}

// C documentation
//
//	/*
//	** Append position iPos to the position list being accumulated in buffer
//	** pBuf, which must be already be large enough to hold the new data.
//	** The previous position written to this list is *piPrev. *piPrev is set
//	** to iPos before returning.
//	*/
func _sqlite3Fts5PoslistSafeAppend(tls *libc.TLS, pBuf uintptr, piPrev uintptr, iPos Ti64) {
	var v1 int32
	var v2 uintptr
	_, _ = v1, v2
	if iPos >= **(**Ti64)(__ccgo_up(piPrev)) {
		if iPos&_colmask != **(**Ti64)(__ccgo_up(piPrev))&_colmask {
			v2 = pBuf + 4
			v1 = *(*int32)(unsafe.Pointer(v2))
			*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
			**(**Tu8)(__ccgo_up((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp + uintptr(v1))) = uint8(1)
			**(**int32)(__ccgo_up(pBuf + 4)) += _sqlite3Fts5PutVarint(tls, (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn), libc.Uint64FromInt64(iPos>>libc.Int32FromInt32(32)))
			**(**Ti64)(__ccgo_up(piPrev)) = iPos & _colmask
		}
		**(**int32)(__ccgo_up(pBuf + 4)) += _sqlite3Fts5PutVarint(tls, (*TFts5Buffer)(unsafe.Pointer(pBuf)).Fp+uintptr((*TFts5Buffer)(unsafe.Pointer(pBuf)).Fn), libc.Uint64FromInt64(iPos-**(**Ti64)(__ccgo_up(piPrev))+int64(2)))
		**(**Ti64)(__ccgo_up(piPrev)) = iPos
	}
}

// C documentation
//
//	/*
//	** Insert a new row into the FTS content table.
//	*/
func _sqlite3Fts5StorageContentInsert(tls *libc.TLS, p uintptr, bReplace int32, apVal uintptr, piRowid uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var bUnindexed, i, iLoc, rc int32
	var pConfig, pVal uintptr
	var _ /* nLoc at bp+16 */ int32
	var _ /* nText at bp+12 */ int32
	var _ /* pInsert at bp+0 */ uintptr
	var _ /* pLoc at bp+8 */ uintptr
	var _ /* pText at bp+4 */ uintptr
	_, _, _, _, _, _ = bUnindexed, i, iLoc, pConfig, pVal, rc
	pConfig = (*TFts5Storage)(unsafe.Pointer(p)).FpConfig
	rc = SQLITE_OK
	/* Insert the new row into the %_content table. */
	if (*TFts5Config)(unsafe.Pointer(pConfig)).FeContent != FTS5_CONTENT_NORMAL && (*TFts5Config)(unsafe.Pointer(pConfig)).FeContent != int32(FTS5_CONTENT_UNINDEXED) {
		if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(apVal + 1*4))) == int32(SQLITE_INTEGER) {
			**(**Ti64)(__ccgo_up(piRowid)) = Xsqlite3_value_int64(tls, **(**uintptr)(__ccgo_up(apVal + 1*4)))
		} else {
			rc = _fts5StorageNewRowid(tls, p, piRowid)
		}
	} else {
		**(**uintptr)(__ccgo_up(bp)) = uintptr(0) /* Counter variable */
		rc = _fts5StorageGetStmt(tls, p, int32(FTS5_STMT_INSERT_CONTENT)+bReplace, bp, uintptr(0))
		if **(**uintptr)(__ccgo_up(bp)) != 0 {
			Xsqlite3_clear_bindings(tls, **(**uintptr)(__ccgo_up(bp)))
		}
		/* Bind the rowid value */
		Xsqlite3_bind_value(tls, **(**uintptr)(__ccgo_up(bp)), int32(1), **(**uintptr)(__ccgo_up(apVal + 1*4)))
		/* Loop through values for user-defined columns. i=2 is the leftmost
		 ** user-defined column. As is column 1 of pSavedRow.  */
		i = int32(2)
		for {
			if !(rc == SQLITE_OK && i <= (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol+int32(1)) {
				break
			}
			bUnindexed = libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Config)(unsafe.Pointer(pConfig)).FabUnindexed + uintptr(i-int32(2)))))
			if (*TFts5Config)(unsafe.Pointer(pConfig)).FeContent == FTS5_CONTENT_NORMAL || bUnindexed != 0 {
				pVal = **(**uintptr)(__ccgo_up(apVal + uintptr(i)*4))
				if Xsqlite3_value_nochange(tls, pVal) != 0 && (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow != 0 {
					/* This is an UPDATE statement, and user-defined column (i-2) was not
					 ** modified.  Retrieve the value from Fts5Storage.pSavedRow.  */
					pVal = Xsqlite3_column_value(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow, i-int32(1))
					if (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 && bUnindexed == 0 {
						Xsqlite3_bind_value(tls, **(**uintptr)(__ccgo_up(bp)), (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol+i, Xsqlite3_column_value(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow, (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol+i-int32(1)))
					}
				} else {
					if _sqlite3Fts5IsLocaleValue(tls, pConfig, pVal) != 0 {
						**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
						**(**uintptr)(__ccgo_up(bp + 8)) = uintptr(0)
						**(**int32)(__ccgo_up(bp + 12)) = 0
						**(**int32)(__ccgo_up(bp + 16)) = 0
						rc = _sqlite3Fts5DecodeLocaleValue(tls, pVal, bp+4, bp+12, bp+8, bp+16)
						if rc == SQLITE_OK {
							Xsqlite3_bind_text(tls, **(**uintptr)(__ccgo_up(bp)), i, **(**uintptr)(__ccgo_up(bp + 4)), **(**int32)(__ccgo_up(bp + 12)), uintptr(-libc.Int32FromInt32(1)))
							if bUnindexed == 0 {
								iLoc = (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol + i
								Xsqlite3_bind_text(tls, **(**uintptr)(__ccgo_up(bp)), iLoc, **(**uintptr)(__ccgo_up(bp + 8)), **(**int32)(__ccgo_up(bp + 16)), uintptr(-libc.Int32FromInt32(1)))
							}
						}
						goto _1
					}
				}
				rc = Xsqlite3_bind_value(tls, **(**uintptr)(__ccgo_up(bp)), i, pVal)
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		if rc == SQLITE_OK {
			Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp)))
			rc = Xsqlite3_reset(tls, **(**uintptr)(__ccgo_up(bp)))
		}
		**(**Ti64)(__ccgo_up(piRowid)) = Xsqlite3_last_insert_rowid(tls, (*TFts5Config)(unsafe.Pointer(pConfig)).Fdb)
	}
	return rc
}

// C documentation
//
//	/*
//	** Insert new entries into the FTS index and %_docsize table.
//	*/
func _sqlite3Fts5StorageIndexInsert(tls *libc.TLS, p uintptr, apVal uintptr, iRowid Ti64) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var iCol int32
	var pConfig, pVal uintptr
	var _ /* buf at bp+16 */ TFts5Buffer
	var _ /* ctx at bp+4 */ TFts5InsertCtx
	var _ /* nLoc at bp+36 */ int32
	var _ /* nText at bp+28 */ int32
	var _ /* pLoc at bp+40 */ uintptr
	var _ /* pText at bp+32 */ uintptr
	var _ /* rc at bp+0 */ int32
	_, _, _ = iCol, pConfig, pVal
	pConfig = (*TFts5Storage)(unsafe.Pointer(p)).FpConfig
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK /* Buffer used to build up %_docsize blob */
	libc.Xmemset(tls, bp+16, 0, uint32(12))
	(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FpStorage = p
	**(**int32)(__ccgo_up(bp)) = _fts5StorageLoadTotals(tls, p, int32(1))
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5IndexBeginWrite(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpIndex, 0, iRowid)
	}
	(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol = 0
	for {
		if !(**(**int32)(__ccgo_up(bp)) == SQLITE_OK && (**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol < (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol) {
			break
		}
		(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FszCol = 0
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Config)(unsafe.Pointer(pConfig)).FabUnindexed + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol)))) == 0 {
			**(**int32)(__ccgo_up(bp + 28)) = 0            /* Size of pText in bytes */
			**(**uintptr)(__ccgo_up(bp + 32)) = uintptr(0) /* Pointer to buffer containing text value */
			**(**int32)(__ccgo_up(bp + 36)) = 0            /* Size of pText in bytes */
			**(**uintptr)(__ccgo_up(bp + 40)) = uintptr(0) /* Pointer to buffer containing text value */
			pVal = **(**uintptr)(__ccgo_up(apVal + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol+int32(2))*4))
			if (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow != 0 && Xsqlite3_value_nochange(tls, pVal) != 0 {
				pVal = Xsqlite3_column_value(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow, (**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol+int32(1))
				if (*TFts5Config)(unsafe.Pointer(pConfig)).FeContent == FTS5_CONTENT_NORMAL && (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 {
					iCol = (**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol + int32(1) + (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol
					**(**uintptr)(__ccgo_up(bp + 40)) = Xsqlite3_column_text(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow, iCol)
					**(**int32)(__ccgo_up(bp + 36)) = Xsqlite3_column_bytes(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpSavedRow, iCol)
				}
			} else {
				pVal = **(**uintptr)(__ccgo_up(apVal + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol+int32(2))*4))
			}
			if (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 && _sqlite3Fts5IsLocaleValue(tls, pConfig, pVal) != 0 {
				**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5DecodeLocaleValue(tls, pVal, bp+32, bp+28, bp+40, bp+36)
			} else {
				**(**uintptr)(__ccgo_up(bp + 32)) = Xsqlite3_value_text(tls, pVal)
				**(**int32)(__ccgo_up(bp + 28)) = Xsqlite3_value_bytes(tls, pVal)
			}
			if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
				_sqlite3Fts5SetLocale(tls, pConfig, **(**uintptr)(__ccgo_up(bp + 40)), **(**int32)(__ccgo_up(bp + 36)))
				**(**int32)(__ccgo_up(bp)) = _sqlite3Fts5Tokenize(tls, pConfig, int32(FTS5_TOKENIZE_DOCUMENT), **(**uintptr)(__ccgo_up(bp + 32)), **(**int32)(__ccgo_up(bp + 28)), bp+4, __ccgo_fp(_fts5StorageInsertCallback))
				_sqlite3Fts5ClearLocale(tls, pConfig)
			}
		}
		_sqlite3Fts5BufferAppendVarint(tls, bp, bp+16, int64((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FszCol))
		**(**Ti64)(__ccgo_up((*TFts5Storage)(unsafe.Pointer(p)).FaTotalSize + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol)*8)) += int64((**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FszCol)
		goto _1
	_1:
		;
		(**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol = (**(**TFts5InsertCtx)(__ccgo_up(bp + 4))).FiCol + 1
	}
	(*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow = (*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow + 1
	/* Write the %_docsize record */
	if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp)) = _fts5StorageInsertDocsize(tls, p, iRowid, bp+16)
	}
	Xsqlite3_free(tls, (**(**TFts5Buffer)(__ccgo_up(bp + 16))).Fp)
	return **(**int32)(__ccgo_up(bp))
}

func _sqlite3Fts5StorageRebuild(tls *libc.TLS, p uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var iCol, rc2 int32
	var iRowid Ti64
	var pConfig, pVal uintptr
	var _ /* buf at bp+0 */ TFts5Buffer
	var _ /* ctx at bp+16 */ TFts5InsertCtx
	var _ /* nLoc at bp+40 */ int32
	var _ /* nText at bp+32 */ int32
	var _ /* pLoc at bp+44 */ uintptr
	var _ /* pScan at bp+12 */ uintptr
	var _ /* pText at bp+36 */ uintptr
	var _ /* rc at bp+28 */ int32
	_, _, _, _, _ = iCol, iRowid, pConfig, pVal, rc2
	**(**TFts5Buffer)(__ccgo_up(bp)) = TFts5Buffer{}
	pConfig = (*TFts5Storage)(unsafe.Pointer(p)).FpConfig
	**(**uintptr)(__ccgo_up(bp + 12)) = uintptr(0)
	libc.Xmemset(tls, bp+16, 0, uint32(12))
	(**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FpStorage = p
	**(**int32)(__ccgo_up(bp + 28)) = _sqlite3Fts5StorageDeleteAll(tls, p)
	if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp + 28)) = _fts5StorageLoadTotals(tls, p, int32(1))
	}
	if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp + 28)) = _fts5StorageGetStmt(tls, p, int32(FTS5_STMT_SCAN), bp+12, (*TFts5Config)(unsafe.Pointer(pConfig)).FpzErrmsg)
	}
	for **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK && int32(SQLITE_ROW) == Xsqlite3_step(tls, **(**uintptr)(__ccgo_up(bp + 12))) {
		iRowid = Xsqlite3_column_int64(tls, **(**uintptr)(__ccgo_up(bp + 12)), 0)
		_sqlite3Fts5BufferZero(tls, bp)
		**(**int32)(__ccgo_up(bp + 28)) = _sqlite3Fts5IndexBeginWrite(tls, (*TFts5Storage)(unsafe.Pointer(p)).FpIndex, 0, iRowid)
		(**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol = 0
		for {
			if !(**(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK && (**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol < (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol) {
				break
			}
			(**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FszCol = 0
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TFts5Config)(unsafe.Pointer(pConfig)).FabUnindexed + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol)))) == 0 {
				**(**int32)(__ccgo_up(bp + 32)) = 0            /* Size of pText in bytes */
				**(**uintptr)(__ccgo_up(bp + 36)) = uintptr(0) /* Pointer to buffer containing text value */
				**(**int32)(__ccgo_up(bp + 40)) = 0            /* Size of pLoc in bytes */
				**(**uintptr)(__ccgo_up(bp + 44)) = uintptr(0) /* Pointer to buffer containing text value */
				pVal = Xsqlite3_column_value(tls, **(**uintptr)(__ccgo_up(bp + 12)), (**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol+int32(1))
				if (*TFts5Config)(unsafe.Pointer(pConfig)).FeContent == int32(FTS5_CONTENT_EXTERNAL) && _sqlite3Fts5IsLocaleValue(tls, pConfig, pVal) != 0 {
					**(**int32)(__ccgo_up(bp + 28)) = _sqlite3Fts5DecodeLocaleValue(tls, pVal, bp+36, bp+32, bp+44, bp+40)
				} else {
					**(**uintptr)(__ccgo_up(bp + 36)) = Xsqlite3_value_text(tls, pVal)
					**(**int32)(__ccgo_up(bp + 32)) = Xsqlite3_value_bytes(tls, pVal)
					if (*TFts5Config)(unsafe.Pointer(pConfig)).FbLocale != 0 {
						iCol = (**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol + int32(1) + (*TFts5Config)(unsafe.Pointer(pConfig)).FnCol
						**(**uintptr)(__ccgo_up(bp + 44)) = Xsqlite3_column_text(tls, **(**uintptr)(__ccgo_up(bp + 12)), iCol)
						**(**int32)(__ccgo_up(bp + 40)) = Xsqlite3_column_bytes(tls, **(**uintptr)(__ccgo_up(bp + 12)), iCol)
					}
				}
				if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
					_sqlite3Fts5SetLocale(tls, pConfig, **(**uintptr)(__ccgo_up(bp + 44)), **(**int32)(__ccgo_up(bp + 40)))
					**(**int32)(__ccgo_up(bp + 28)) = _sqlite3Fts5Tokenize(tls, pConfig, int32(FTS5_TOKENIZE_DOCUMENT), **(**uintptr)(__ccgo_up(bp + 36)), **(**int32)(__ccgo_up(bp + 32)), bp+16, __ccgo_fp(_fts5StorageInsertCallback))
					_sqlite3Fts5ClearLocale(tls, pConfig)
				}
			}
			_sqlite3Fts5BufferAppendVarint(tls, bp+28, bp, int64((**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FszCol))
			**(**Ti64)(__ccgo_up((*TFts5Storage)(unsafe.Pointer(p)).FaTotalSize + uintptr((**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol)*8)) += int64((**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FszCol)
			goto _1
		_1:
			;
			(**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol = (**(**TFts5InsertCtx)(__ccgo_up(bp + 16))).FiCol + 1
		}
		(*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow = (*TFts5Storage)(unsafe.Pointer(p)).FnTotalRow + 1
		if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
			**(**int32)(__ccgo_up(bp + 28)) = _fts5StorageInsertDocsize(tls, p, iRowid, bp)
		}
	}
	Xsqlite3_free(tls, (**(**TFts5Buffer)(__ccgo_up(bp))).Fp)
	rc2 = Xsqlite3_reset(tls, **(**uintptr)(__ccgo_up(bp + 12)))
	if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp + 28)) = rc2
	}
	/* Write the averages record */
	if **(**int32)(__ccgo_up(bp + 28)) == SQLITE_OK {
		**(**int32)(__ccgo_up(bp + 28)) = _fts5StorageSaveTotals(tls, p)
	}
	return **(**int32)(__ccgo_up(bp + 28))
}

func _sqlite3Fts5TermsetFree(tls *libc.TLS, p uintptr) {
	var i Tu32
	var pDel, pEntry uintptr
	_, _, _ = i, pDel, pEntry
	if p != 0 {
		i = uint32(0)
		for {
			if !(i < libc.Uint32FromInt32(libc.Int32FromUint32(libc.Uint32FromInt64(2048)/libc.Uint32FromInt64(4)))) {
				break
			}
			pEntry = **(**uintptr)(__ccgo_up(p + uintptr(i)*4))
			for pEntry != 0 {
				pDel = pEntry
				pEntry = (*TFts5TermsetEntry)(unsafe.Pointer(pEntry)).FpNext
				Xsqlite3_free(tls, pDel)
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		Xsqlite3_free(tls, p)
	}
}

/*
** 2014 Jun 09
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is an SQLite module implementing full-text search.
 */

/* #include "fts5Int.h" */

/* Maximum allowed page size */

// C documentation
//
//	/*
//	** Interpret the argument as a unicode codepoint. If the codepoint
//	** is an upper case character that has a lower case equivalent,
//	** return the codepoint corresponding to the lower case version.
//	** Otherwise, return a copy of the argument.
//	**
//	** The results are undefined if the value passed to this function
//	** is less than zero.
//	*/
func _sqlite3Fts5UnicodeFold(tls *libc.TLS, c int32, eRemoveDiacritic int32) (r int32) {
	var cmp, iHi, iLo, iRes, iTest, ret int32
	var p uintptr
	_, _, _, _, _, _, _ = cmp, iHi, iLo, iRes, iTest, p, ret
	ret = c
	if c < int32(128) {
		if c >= int32('A') && c <= int32('Z') {
			ret = c + (libc.Int32FromUint8('a') - libc.Int32FromUint8('A'))
		}
	} else {
		if c < int32(65536) {
			iHi = libc.Int32FromUint32(libc.Uint32FromInt64(652)/libc.Uint32FromInt64(4) - libc.Uint32FromInt32(1))
			iLo = 0
			iRes = -int32(1)
			for iHi >= iLo {
				iTest = (iHi + iLo) / int32(2)
				cmp = c - libc.Int32FromUint16(_aEntry[iTest].FiCode)
				if cmp >= 0 {
					iRes = iTest
					iLo = iTest + int32(1)
				} else {
					iHi = iTest - int32(1)
				}
			}
			p = uintptr(unsafe.Pointer(&_aEntry)) + uintptr(iRes)*4
			if c < libc.Int32FromUint16((*struct {
				FiCode  uint16
				Fflags  uint8
				FnRange uint8
			})(unsafe.Pointer(p)).FiCode)+libc.Int32FromUint8((*struct {
				FiCode  uint16
				Fflags  uint8
				FnRange uint8
			})(unsafe.Pointer(p)).FnRange) && 0 == int32(0x01)&libc.Int32FromUint8((*struct {
				FiCode  uint16
				Fflags  uint8
				FnRange uint8
			})(unsafe.Pointer(p)).Fflags)&(libc.Int32FromUint16((*struct {
				FiCode  uint16
				Fflags  uint8
				FnRange uint8
			})(unsafe.Pointer(p)).FiCode)^c) {
				ret = (c + libc.Int32FromUint16(_aiOff[libc.Int32FromUint8((*struct {
					FiCode  uint16
					Fflags  uint8
					FnRange uint8
				})(unsafe.Pointer(p)).Fflags)>>int32(1)])) & int32(0x0000FFFF)
			}
			if eRemoveDiacritic != 0 {
				ret = _fts5_remove_diacritic(tls, ret, libc.BoolInt32(eRemoveDiacritic == int32(2)))
			}
		} else {
			if c >= int32(66560) && c < int32(66600) {
				ret = c + int32(40)
			}
		}
	}
	return ret
}

// C documentation
//
//	/*
//	** Generate code that will assemble an index key and stores it in register
//	** regOut.  The key with be for index pIdx which is an index on pTab.
//	** iCur is the index of a cursor open on the pTab table and pointing to
//	** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
//	** iCur must be the cursor of the PRIMARY KEY index.
//	**
//	** Return a register number which is the first in a block of
//	** registers that holds the elements of the index key.  The
//	** block of registers has already been deallocated by the time
//	** this routine returns.
//	**
//	** If *piPartIdxLabel is not NULL, fill it in with a label and jump
//	** to that label if pIdx is a partial index that should be skipped.
//	** The label should be resolved using sqlite3ResolvePartIdxLabel().
//	** A partial index should be skipped if its WHERE clause evaluates
//	** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
//	** will be set to zero which is an empty label that is ignored by
//	** sqlite3ResolvePartIdxLabel().
//	**
//	** The pPrior and regPrior parameters are used to implement a cache to
//	** avoid unnecessary register loads.  If pPrior is not NULL, then it is
//	** a pointer to a different index for which an index key has just been
//	** computed into register regPrior.  If the current pIdx index is generating
//	** its key into the same sequence of registers and if pPrior and pIdx share
//	** a column in common, then the register corresponding to that column already
//	** holds the correct value and the loading of that register is skipped.
//	** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
//	** on a table with multiple indices, and especially with the ROWID or
//	** PRIMARY KEY columns of the index.
//	*/
func _sqlite3GenerateIndexKey(tls *libc.TLS, pParse uintptr, pIdx uintptr, iDataCur int32, regOut int32, prefixOnly int32, piPartIdxLabel uintptr, pPrior uintptr, regPrior int32) (r int32) {
	var j, nCol, regBase, v1 int32
	var v uintptr
	_, _, _, _, _ = j, nCol, regBase, v, v1
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	if piPartIdxLabel != 0 {
		if (*TIndex)(unsafe.Pointer(pIdx)).FpPartIdxWhere != 0 {
			**(**int32)(__ccgo_up(piPartIdxLabel)) = _sqlite3VdbeMakeLabel(tls, pParse)
			(*TParse)(unsafe.Pointer(pParse)).FiSelfTab = iDataCur + int32(1)
			_sqlite3ExprIfFalseDup(tls, pParse, (*TIndex)(unsafe.Pointer(pIdx)).FpPartIdxWhere, **(**int32)(__ccgo_up(piPartIdxLabel)), int32(SQLITE_JUMPIFNULL))
			(*TParse)(unsafe.Pointer(pParse)).FiSelfTab = 0
			pPrior = uintptr(0) /* Ticket a9efb42811fa41ee 2019-11-02;
			 ** pPartIdxWhere may have corrupted regPrior registers */
		} else {
			**(**int32)(__ccgo_up(piPartIdxLabel)) = 0
		}
	}
	if prefixOnly != 0 && int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x8>>3)) != 0 {
		v1 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
	} else {
		v1 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
	}
	nCol = v1
	regBase = _sqlite3GetTempRange(tls, pParse, nCol)
	if pPrior != 0 && (regBase != regPrior || (*TIndex)(unsafe.Pointer(pPrior)).FpPartIdxWhere != 0) {
		pPrior = uintptr(0)
	}
	j = 0
	for {
		if !(j < nCol) {
			break
		}
		if pPrior != 0 && int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pPrior)).FaiColumn + uintptr(j)*2))) == int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(j)*2))) && int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pPrior)).FaiColumn + uintptr(j)*2))) != -int32(2) {
			/* This column was already computed by the previous index */
			goto _2
		}
		_sqlite3ExprCodeLoadIndexColumn(tls, pParse, pIdx, iDataCur, j, regBase+j)
		if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(j)*2))) >= 0 {
			/* If the column affinity is REAL but the number is an integer, then it
			 ** might be stored in the table as an integer (using a compact
			 ** representation) then converted to REAL by an OP_RealAffinity opcode.
			 ** But we are getting ready to store this value back into an index, where
			 ** it should be converted by to INTEGER again.  So omit the
			 ** OP_RealAffinity opcode if it is present */
			_sqlite3VdbeDeletePriorOpcode(tls, v, uint8(OP_RealAffinity))
		}
		goto _2
	_2:
		;
		j = j + 1
	}
	if regOut != 0 {
		_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), regBase, nCol, regOut)
	}
	_sqlite3ReleaseTempRange(tls, pParse, regBase, nCol)
	return regBase
}

// C documentation
//
//	/*
//	** This routine generates VDBE code that causes the deletion of all
//	** index entries associated with a single row of a single table, pTab
//	**
//	** Preconditions:
//	**
//	**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
//	**       btree for the table pTab.  (This will be either the table itself
//	**       for rowid tables or to the primary key index for WITHOUT ROWID
//	**       tables.)
//	**
//	**   2.  Read/write cursors for all indices of pTab must be open as
//	**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
//	**       index is the 0-th index.)
//	**
//	**   3.  The "iDataCur" cursor must be already be positioned on the row
//	**       that is to be deleted.
//	*/
func _sqlite3GenerateRowIndexDelete(tls *libc.TLS, pParse uintptr, pTab uintptr, iDataCur int32, iIdxCur int32, aRegIdx uintptr, iIdxNoSeek int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, r1, v3 int32
	var pIdx, pPk, pPrior, v, v1 uintptr
	var _ /* iPartIdxLabel at bp+0 */ int32
	_, _, _, _, _, _, _, _ = i, pIdx, pPk, pPrior, r1, v, v1, v3 /* Index loop counter */
	r1 = -int32(1)                                               /* Current index */
	pPrior = uintptr(0)                                          /* PRIMARY KEY index, or NULL for rowid tables */
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_WithoutRowid) == uint32(0) {
		v1 = uintptr(0)
	} else {
		v1 = _sqlite3PrimaryKeyIndex(tls, pTab)
	}
	pPk = v1
	i = 0
	pIdx = (*TTable)(unsafe.Pointer(pTab)).FpIndex
	for {
		if !(pIdx != 0) {
			break
		}
		if aRegIdx != uintptr(0) && **(**int32)(__ccgo_up(aRegIdx + uintptr(i)*4)) == 0 {
			goto _2
		}
		if pIdx == pPk {
			goto _2
		}
		if iIdxCur+i == iIdxNoSeek {
			goto _2
		}
		r1 = _sqlite3GenerateIndexKey(tls, pParse, pIdx, iDataCur, 0, int32(1), bp, pPrior, r1)
		if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x8>>3)) != 0 {
			v3 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
		} else {
			v3 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
		}
		_sqlite3VdbeAddOp3(tls, v, int32(OP_IdxDelete), iIdxCur+i, r1, v3)
		_sqlite3VdbeChangeP4(tls, v, -int32(1), pIdx, -int32(6))
		_sqlite3ResolvePartIdxLabel(tls, pParse, **(**int32)(__ccgo_up(bp)))
		pPrior = pIdx
		goto _2
	_2:
		;
		i = i + 1
		pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
	}
}

// C documentation
//
//	/*
//	** Allocate a single new register for use to hold some intermediate result.
//	*/
func _sqlite3GetTempReg(tls *libc.TLS, pParse uintptr) (r int32) {
	var v1 int32
	var v2 uintptr
	var v3 Tu8
	_, _, _ = v1, v2, v3
	if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FnTempReg) == 0 {
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		return v1
	}
	v2 = pParse + 19
	*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) - 1
	v3 = *(*Tu8)(unsafe.Pointer(v2))
	return **(**int32)(__ccgo_up(pParse + 136 + uintptr(v3)*4))
}

// C documentation
//
//	/*
//	** Get a VDBE for the given parser context.  Create a new one if necessary.
//	** If an error occurs, return NULL and leave a message in pParse.
//	*/
func _sqlite3GetVdbe(tls *libc.TLS, pParse uintptr) (r uintptr) {
	if (*TParse)(unsafe.Pointer(pParse)).FpVdbe != 0 {
		return (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	}
	if (*TParse)(unsafe.Pointer(pParse)).FpToplevel == uintptr(0) && (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_FactorOutConst)) == uint32(0) {
		libc.SetBitFieldPtr16Uint32(pParse+28, libc.Uint32FromInt32(1), 7, 0x80)
	}
	return _sqlite3VdbeCreate(tls, pParse)
}

// C documentation
//
//	/*
//	** Return the size of the header added to each page by this module.
//	*/
func _sqlite3HeaderSizeBtree(tls *libc.TLS) (r int32) {
	return libc.Int32FromUint32((libc.Uint32FromInt64(84) + libc.Uint32FromInt32(7)) & libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
}

// C documentation
//
//	/*
//	** Return the size of the header added by this middleware layer
//	** in the page-cache hierarchy.
//	*/
func _sqlite3HeaderSizePcache(tls *libc.TLS) (r int32) {
	return libc.Int32FromUint32((libc.Uint32FromInt64(48) + libc.Uint32FromInt32(7)) & libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
}

// C documentation
//
//	/*
//	** Return the size of the header on each page of this PCACHE implementation.
//	*/
func _sqlite3HeaderSizePcache1(tls *libc.TLS) (r int32) {
	return libc.Int32FromUint32((libc.Uint32FromInt64(32) + libc.Uint32FromInt32(7)) & libc.Uint32FromInt32(^libc.Int32FromInt32(7)))
}

// C documentation
//
//	/*
//	** Append a new element to the given IdList.  Create a new IdList if
//	** need be.
//	**
//	** A new IdList is returned, or NULL if malloc() fails.
//	*/
func _sqlite3IdListAppend(tls *libc.TLS, pParse uintptr, pList uintptr, pToken uintptr) (r uintptr) {
	var db, pNew, v2 uintptr
	var i, v1 int32
	_, _, _, _, _ = db, i, pNew, v1, v2
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	if pList == uintptr(0) {
		pList = _sqlite3DbMallocZero(tls, db, uint64(uint32(libc.UintptrFromInt32(0)+4)+libc.Uint32FromInt32(libc.Int32FromInt32(1))*libc.Uint32FromInt64(4)))
		if pList == uintptr(0) {
			return uintptr(0)
		}
	} else {
		pNew = _sqlite3DbRealloc(tls, db, pList, uint64(uint32(libc.UintptrFromInt32(0)+4)+libc.Uint32FromInt32((*TIdList)(unsafe.Pointer(pList)).FnId+libc.Int32FromInt32(1))*libc.Uint32FromInt64(4)))
		if pNew == uintptr(0) {
			_sqlite3IdListDelete(tls, db, pList)
			return uintptr(0)
		}
		pList = pNew
	}
	v2 = pList
	v1 = *(*int32)(unsafe.Pointer(v2))
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	i = v1
	(*(*TIdList_item)(unsafe.Pointer(pList + 4 + uintptr(i)*4))).FzName = _sqlite3NameFromToken(tls, db, pToken)
	if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) >= int32(PARSE_MODE_RENAME) && (*(*TIdList_item)(unsafe.Pointer(pList + 4 + uintptr(i)*4))).FzName != 0 {
		_sqlite3RenameTokenMap(tls, pParse, (*(*TIdList_item)(unsafe.Pointer(pList + 4 + uintptr(i)*4))).FzName, pToken)
	}
	return pList
}

func _sqlite3IdListDup(tls *libc.TLS, db uintptr, p uintptr) (r uintptr) {
	var i int32
	var pNew, pNewItem, pOldItem uintptr
	_, _, _, _ = i, pNew, pNewItem, pOldItem
	if p == uintptr(0) {
		return uintptr(0)
	}
	pNew = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(libc.UintptrFromInt32(0)+4)+libc.Uint32FromInt32((*TIdList)(unsafe.Pointer(p)).FnId)*libc.Uint32FromInt64(4)))
	if pNew == uintptr(0) {
		return uintptr(0)
	}
	(*TIdList)(unsafe.Pointer(pNew)).FnId = (*TIdList)(unsafe.Pointer(p)).FnId
	i = 0
	for {
		if !(i < (*TIdList)(unsafe.Pointer(p)).FnId) {
			break
		}
		pNewItem = pNew + 4 + uintptr(i)*4
		pOldItem = p + 4 + uintptr(i)*4
		(*TIdList_item)(unsafe.Pointer(pNewItem)).FzName = _sqlite3DbStrDup(tls, db, (*TIdList_item)(unsafe.Pointer(pOldItem)).FzName)
		goto _1
	_1:
		;
		i = i + 1
	}
	return pNew
}

// C documentation
//
//	/*
//	** Initialize all database files - the main database file, the file
//	** used to store temporary tables, and any additional database files
//	** created using ATTACH statements.  Return a success code.  If an
//	** error occurs, write an error message into *pzErrMsg.
//	**
//	** After a database is initialized, the DB_SchemaLoaded bit is set
//	** bit is set in the flags field of the Db structure.
//	*/
func _sqlite3Init(tls *libc.TLS, db uintptr, pzErrMsg uintptr) (r int32) {
	var commit_internal, i, rc int32
	_, _, _ = commit_internal, i, rc
	commit_internal = libc.BoolInt32(!((*Tsqlite3)(unsafe.Pointer(db)).FmDbFlags&libc.Uint32FromInt32(DBFLAG_SchemaChange) != 0))
	(*Tsqlite3)(unsafe.Pointer(db)).Fenc = (*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb))).FpSchema)).Fenc
	/* Do the main schema first */
	if !(libc.Int32FromUint16((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb))).FpSchema)).FschemaFlags)&libc.Int32FromInt32(DB_SchemaLoaded) == libc.Int32FromInt32(DB_SchemaLoaded)) {
		rc = _sqlite3InitOne(tls, db, 0, pzErrMsg, uint32(0))
		if rc != 0 {
			return rc
		}
	}
	/* All other schemas after the main schema. The "temp" schema must be last */
	i = (*Tsqlite3)(unsafe.Pointer(db)).FnDb - int32(1)
	for {
		if !(i > 0) {
			break
		}
		if !(libc.Int32FromUint16((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(i)*16))).FpSchema)).FschemaFlags)&libc.Int32FromInt32(DB_SchemaLoaded) == libc.Int32FromInt32(DB_SchemaLoaded)) {
			rc = _sqlite3InitOne(tls, db, i, pzErrMsg, uint32(0))
			if rc != 0 {
				return rc
			}
		}
		goto _1
	_1:
		;
		i = i - 1
	}
	if commit_internal != 0 {
		_sqlite3CommitInternalChanges(tls, db)
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
//	** defined in pager.h. This function returns the associated lowercase
//	** journal-mode name.
//	*/
func _sqlite3JournalModename(tls *libc.TLS, eMode int32) (r uintptr) {
	if eMode == libc.Int32FromUint32(libc.Uint32FromInt64(24)/libc.Uint32FromInt64(4)) {
		return uintptr(0)
	}
	return _azModeName[eMode]
}

// C documentation
//
//	/*
//	** Allocate a KeyInfo object sufficient for an index of N key columns and
//	** X extra columns.
//	*/
func _sqlite3KeyInfoAlloc(tls *libc.TLS, db uintptr, N int32, X int32) (r uintptr) {
	var nExtra int32
	var p uintptr
	_, _ = nExtra, p
	nExtra = libc.Int32FromUint32(libc.Uint32FromInt32(N+X) * (libc.Uint32FromInt64(4) + libc.Uint32FromInt32(1)))
	if N+X > int32(0xffff) {
		return _sqlite3OomFault(tls, db)
	}
	p = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(libc.UintptrFromInt32(0)+20)+libc.Uint32FromInt32(libc.Int32FromInt32(0))*libc.Uint32FromInt64(4)+libc.Uint32FromInt32(nExtra)))
	if p != 0 {
		(*TKeyInfo)(unsafe.Pointer(p)).FaSortFlags = p + 20 + uintptr(N+X)*4
		(*TKeyInfo)(unsafe.Pointer(p)).FnKeyField = libc.Uint16FromInt32(N)
		(*TKeyInfo)(unsafe.Pointer(p)).FnAllField = libc.Uint16FromInt32(N + X)
		(*TKeyInfo)(unsafe.Pointer(p)).Fenc = (*Tsqlite3)(unsafe.Pointer(db)).Fenc
		(*TKeyInfo)(unsafe.Pointer(p)).Fdb = db
		(*TKeyInfo)(unsafe.Pointer(p)).FnRef = uint32(1)
		libc.Xmemset(tls, p+20, 0, libc.Uint32FromInt32(nExtra))
	} else {
		return _sqlite3OomFault(tls, db)
	}
	return p
}

// C documentation
//
//	/*
//	** Return a KeyInfo structure that is appropriate for the given Index.
//	**
//	** The caller should invoke sqlite3KeyInfoUnref() on the returned object
//	** when it has finished using it.
//	*/
func _sqlite3KeyInfoOfIndex(tls *libc.TLS, pParse uintptr, pIdx uintptr) (r uintptr) {
	var i, nCol, nKey int32
	var pKey, zColl, v2 uintptr
	_, _, _, _, _, _ = i, nCol, nKey, pKey, zColl, v2
	nCol = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
	nKey = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		return uintptr(0)
	}
	if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x8>>3)) != 0 {
		pKey = _sqlite3KeyInfoAlloc(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, nKey, nCol-nKey)
	} else {
		pKey = _sqlite3KeyInfoAlloc(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, nCol, 0)
	}
	if pKey != 0 {
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			zColl = **(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FazColl + uintptr(i)*4))
			if zColl == uintptr(unsafe.Pointer(&_sqlite3StrBINARY)) {
				v2 = uintptr(0)
			} else {
				v2 = _sqlite3LocateCollSeq(tls, pParse, zColl)
			}
			*(*uintptr)(unsafe.Pointer(pKey + 20 + uintptr(i)*4)) = v2
			**(**Tu8)(__ccgo_up((*TKeyInfo)(unsafe.Pointer(pKey)).FaSortFlags + uintptr(i))) = **(**Tu8)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaSortOrder + uintptr(i)))
			goto _1
		_1:
			;
			i = i + 1
		}
		if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
			if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x100>>8)) == 0 && _sqlite3HashFind(tls, (*TIndex)(unsafe.Pointer(pIdx)).FpSchema+24, (*TIndex)(unsafe.Pointer(pIdx)).FzName) != 0 {
				/* Deactivate the index because it contains an unknown collating
				 ** sequence.  The only way to reactive the index is to reload the
				 ** schema.  Adding the missing collating sequence later does not
				 ** reactive the index.  The application had the chance to register
				 ** the missing index using the collation-needed callback.  For
				 ** simplicity, SQLite will not give the application a second chance.
				 **
				 ** Except, do not do this if the index is not in the schema hash
				 ** table. In this case the index is currently being constructed
				 ** by a CREATE INDEX statement, and retrying will not help.  */
				libc.SetBitFieldPtr16Uint32(pIdx+56, libc.Uint32FromInt32(1), 8, 0x100)
				(*TParse)(unsafe.Pointer(pParse)).Frc = libc.Int32FromInt32(SQLITE_ERROR) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
			}
			_sqlite3KeyInfoUnref(tls, pKey)
			pKey = uintptr(0)
		}
	}
	return pKey
}

// C documentation
//
//	/*
//	** Convert a double into a LogEst
//	** In other words, compute an approximation for 10*log2(x).
//	*/
func _sqlite3LogEstFromDouble(tls *libc.TLS, _x float64) (r TLogEst) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	*(*float64)(unsafe.Pointer(bp)) = _x
	var e TLogEst
	var _ /* a at bp+8 */ Tu64
	_ = e
	if **(**float64)(__ccgo_up(bp)) <= libc.Float64FromInt32(1) {
		return 0
	}
	if **(**float64)(__ccgo_up(bp)) <= libc.Float64FromInt32(2000000000) {
		return _sqlite3LogEst(tls, uint64(**(**float64)(__ccgo_up(bp))))
	}
	libc.Xmemcpy(tls, bp+8, bp, uint32(8))
	e = libc.Int16FromUint64(**(**Tu64)(__ccgo_up(bp + 8))>>libc.Int32FromInt32(52) - uint64(1022))
	return int16(int32(e) * int32(10))
}

// C documentation
//
//	/*
//	** This routine is called when the extension is loaded.
//	** Register the new VFS.
//	*/
func _sqlite3MemdbInit(tls *libc.TLS) (r int32) {
	var pLower uintptr
	var sz uint32
	_, _ = pLower, sz
	pLower = Xsqlite3_vfs_find(tls, uintptr(0))
	if pLower == uintptr(0) {
		return int32(SQLITE_ERROR)
	}
	sz = libc.Uint32FromInt32((*Tsqlite3_vfs)(unsafe.Pointer(pLower)).FszOsFile)
	_memdb_vfs.FpAppData = pLower
	/* The following conditional can only be true when compiled for
	 ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0.  We always leave
	 ** it in, to be safe, but it is marked as NO_TEST since there
	 ** is no way to reach it under most builds. */
	if sz < uint32(12) {
		sz = uint32(12)
	} /*NO_TEST*/
	_memdb_vfs.FszOsFile = libc.Int32FromUint32(sz)
	return Xsqlite3_vfs_register(tls, uintptr(unsafe.Pointer(&_memdb_vfs)), 0)
}

// C documentation
//
//	/*
//	** This function is called by the parser for the second and subsequent
//	** rows of a multi-row VALUES clause. Argument pLeft is the part of
//	** the VALUES clause already parsed, argument pRow is the vector of values
//	** for the new row. The Select object returned represents the complete
//	** VALUES clause, including the new row.
//	**
//	** There are two ways in which this may be achieved - by incremental
//	** coding of a co-routine (the "co-routine" method) or by returning a
//	** Select object equivalent to the following (the "UNION ALL" method):
//	**
//	**        "pLeft UNION ALL SELECT pRow"
//	**
//	** If the VALUES clause contains a lot of rows, this compound Select
//	** object may consume a lot of memory.
//	**
//	** When the co-routine method is used, each row that will be returned
//	** by the VALUES clause is coded into part of a co-routine as it is
//	** passed to this function. The returned Select object is equivalent to:
//	**
//	**     SELECT * FROM (
//	**       Select object to read co-routine
//	**     )
//	**
//	** The co-routine method is used in most cases. Exceptions are:
//	**
//	**    a) If the current statement has a WITH clause. This is to avoid
//	**       statements like:
//	**
//	**            WITH cte AS ( VALUES('x'), ('y') ... )
//	**            SELECT * FROM cte AS a, cte AS b;
//	**
//	**       This will not work, as the co-routine uses a hard-coded register
//	**       for its OP_Yield instructions, and so it is not possible for two
//	**       cursors to iterate through it concurrently.
//	**
//	**    b) The schema is currently being parsed (i.e. the VALUES clause is part
//	**       of a schema item like a VIEW or TRIGGER). In this case there is no VM
//	**       being generated when parsing is taking place, and so generating
//	**       a co-routine is not possible.
//	**
//	**    c) There are non-constant expressions in the VALUES clause (e.g.
//	**       the VALUES clause is part of a correlated sub-query).
//	**
//	**    d) One or more of the values in the first row of the VALUES clause
//	**       has an affinity (i.e. is a CAST expression). This causes problems
//	**       because the complex rules SQLite uses (see function
//	**       sqlite3SubqueryColumnTypes() in select.c) to determine the effective
//	**       affinity of such a column for all rows require access to all values in
//	**       the column simultaneously.
//	*/
func _sqlite3MultiValues(tls *libc.TLS, pParse uintptr, pLeft uintptr, pRow uintptr) (r uintptr) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var f, v1 int32
	var p, pRet, pSelect, pSubq, pSubq1, v, v2 uintptr
	var _ /* dest at bp+0 */ TSelectDest
	_, _, _, _, _, _, _, _, _ = f, p, pRet, pSelect, pSubq, pSubq1, v, v1, v2
	if int32(Tbft(*(*uint16)(unsafe.Pointer(pParse + 28))&0x40>>6)) != 0 || (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).Finit1.Fbusy != 0 || _exprListIsConstant(tls, pParse, pRow) == 0 || (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pLeft)).FpSrc)).FnSrc == 0 && _exprListIsNoAffinity(tls, pParse, (*TSelect)(unsafe.Pointer(pLeft)).FpEList) == 0 || libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) != PARSE_MODE_NORMAL {
		/* The co-routine method cannot be used. Fall back to UNION ALL. */
		pSelect = uintptr(0)
		f = libc.Int32FromInt32(SF_Values) | libc.Int32FromInt32(SF_MultiValue)
		if (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pLeft)).FpSrc)).FnSrc != 0 {
			_sqlite3MultiValuesEnd(tls, pParse, pLeft)
			f = int32(SF_Values)
		} else {
			if (*TSelect)(unsafe.Pointer(pLeft)).FpPrior != 0 {
				/* In this case set the SF_MultiValue flag only if it was set on pLeft */
				f = libc.Int32FromUint32(libc.Uint32FromInt32(f) & (*TSelect)(unsafe.Pointer(pLeft)).FselFlags)
			}
		}
		pSelect = _sqlite3SelectNew(tls, pParse, pRow, uintptr(0), uintptr(0), uintptr(0), uintptr(0), uintptr(0), libc.Uint32FromInt32(f), uintptr(0))
		**(**Tu32)(__ccgo_up(pLeft + 4)) &= ^libc.Uint32FromInt32(SF_MultiValue)
		if pSelect != 0 {
			(*TSelect)(unsafe.Pointer(pSelect)).Fop = uint8(TK_ALL)
			(*TSelect)(unsafe.Pointer(pSelect)).FpPrior = pLeft
			pLeft = pSelect
		}
	} else {
		p = uintptr(0) /* SrcItem that reads from co-routine */
		if (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pLeft)).FpSrc)).FnSrc == 0 {
			/* Co-routine has not yet been started and the special Select object
			 ** that accesses the co-routine has not yet been created. This block
			 ** does both those things. */
			v = _sqlite3GetVdbe(tls, pParse)
			pRet = _sqlite3SelectNew(tls, pParse, uintptr(0), uintptr(0), uintptr(0), uintptr(0), uintptr(0), uintptr(0), uint32(0), uintptr(0))
			/* Ensure the database schema has been read. This is to ensure we have
			 ** the correct text encoding.  */
			if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmDbFlags&uint32(DBFLAG_SchemaKnownOk) == uint32(0) {
				_sqlite3ReadSchema(tls, pParse)
			}
			if pRet != 0 {
				(*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pRet)).FpSrc)).FnSrc = int32(1)
				(*TSelect)(unsafe.Pointer(pRet)).FpPrior = (*TSelect)(unsafe.Pointer(pLeft)).FpPrior
				(*TSelect)(unsafe.Pointer(pRet)).Fop = (*TSelect)(unsafe.Pointer(pLeft)).Fop
				if (*TSelect)(unsafe.Pointer(pRet)).FpPrior != 0 {
					**(**Tu32)(__ccgo_up(pRet + 4)) |= uint32(SF_Values)
				}
				(*TSelect)(unsafe.Pointer(pLeft)).FpPrior = uintptr(0)
				(*TSelect)(unsafe.Pointer(pLeft)).Fop = uint8(TK_SELECT)
				p = (*TSelect)(unsafe.Pointer(pRet)).FpSrc + 8
				libc.SetBitFieldPtr32Uint32(p+12+4, libc.Uint32FromInt32(1), 6, 0x40)
				(*TSrcItem)(unsafe.Pointer(p)).FiCursor = -int32(1)
				*(*Tu32)(unsafe.Pointer(p + 32)) = uint32(2)
				if _sqlite3SrcItemAttachSubquery(tls, pParse, p, pLeft, 0) != 0 {
					pSubq = *(*uintptr)(unsafe.Pointer(p + 44))
					(*TSubquery)(unsafe.Pointer(pSubq)).FaddrFillSub = _sqlite3VdbeCurrentAddr(tls, v) + int32(1)
					v2 = pParse + 48
					*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
					v1 = *(*int32)(unsafe.Pointer(v2))
					(*TSubquery)(unsafe.Pointer(pSubq)).FregReturn = v1
					_sqlite3VdbeAddOp3(tls, v, int32(OP_InitCoroutine), (*TSubquery)(unsafe.Pointer(pSubq)).FregReturn, 0, (*TSubquery)(unsafe.Pointer(pSubq)).FaddrFillSub)
					_sqlite3SelectDestInit(tls, bp, int32(SRT_Coroutine), (*TSubquery)(unsafe.Pointer(pSubq)).FregReturn)
					/* Allocate registers for the output of the co-routine. Do so so
					 ** that there are two unused registers immediately before those
					 ** used by the co-routine. This allows the code in sqlite3Insert()
					 ** to use these registers directly, instead of copying the output
					 ** of the co-routine to a separate array for processing.  */
					(**(**TSelectDest)(__ccgo_up(bp))).FiSdst = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(3)
					(**(**TSelectDest)(__ccgo_up(bp))).FnSdst = (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pLeft)).FpEList)).FnExpr
					**(**int32)(__ccgo_up(pParse + 48)) += int32(2) + (**(**TSelectDest)(__ccgo_up(bp))).FnSdst
					**(**Tu32)(__ccgo_up(pLeft + 4)) |= uint32(SF_MultiValue)
					_sqlite3Select(tls, pParse, pLeft, bp)
					(*TSubquery)(unsafe.Pointer(pSubq)).FregResult = (**(**TSelectDest)(__ccgo_up(bp))).FiSdst
				}
				pLeft = pRet
			}
		} else {
			p = (*TSelect)(unsafe.Pointer(pLeft)).FpSrc + 8
			*(*Tu32)(unsafe.Pointer(p + 32)) = *(*Tu32)(unsafe.Pointer(p + 32)) + 1
		}
		if (*TParse)(unsafe.Pointer(pParse)).FnErr == 0 {
			pSubq1 = *(*uintptr)(unsafe.Pointer(p + 44))
			if (*TExprList)(unsafe.Pointer((*TSelect)(unsafe.Pointer((*TSubquery)(unsafe.Pointer(pSubq1)).FpSelect)).FpEList)).FnExpr != (*TExprList)(unsafe.Pointer(pRow)).FnExpr {
				_sqlite3SelectWrongNumTermsError(tls, pParse, (*TSubquery)(unsafe.Pointer(pSubq1)).FpSelect)
			} else {
				_sqlite3ExprCodeExprList(tls, pParse, pRow, (*TSubquery)(unsafe.Pointer(pSubq1)).FregResult, 0, uint8(0))
				_sqlite3VdbeAddOp1(tls, (*TParse)(unsafe.Pointer(pParse)).FpVdbe, int32(OP_Yield), (*TSubquery)(unsafe.Pointer(pSubq1)).FregReturn)
			}
		}
		_sqlite3ExprListDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pRow)
	}
	return pLeft
}

// C documentation
//
//	/*
//	** Allocate cursors for the pTab table and all its indices and generate
//	** code to open and initialized those cursors.
//	**
//	** The cursor for the object that contains the complete data (normally
//	** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
//	** ROWID table) is returned in *piDataCur.  The first index cursor is
//	** returned in *piIdxCur.  The number of indices is returned.
//	**
//	** Use iBase as the first cursor (either the *piDataCur for rowid tables
//	** or the first index for WITHOUT ROWID tables) if it is non-negative.
//	** If iBase is negative, then allocate the next available cursor.
//	**
//	** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
//	** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
//	** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
//	** pTab->pIndex list.
//	**
//	** If pTab is a virtual table, then this routine is a no-op and the
//	** *piDataCur and *piIdxCur values are left uninitialized.
//	*/
func _sqlite3OpenTableAndIndices(tls *libc.TLS, pParse uintptr, pTab uintptr, op int32, p5 Tu8, iBase int32, aToOpen uintptr, piDataCur uintptr, piIdxCur uintptr) (r int32) {
	var i, iDataCur, iDb, iIdxCur, v1 int32
	var pIdx, v uintptr
	_, _, _, _, _, _, _ = i, iDataCur, iDb, iIdxCur, pIdx, v, v1
	if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VTAB) {
		/* This routine is a no-op for virtual tables. Leave the output
		 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
		 ** for improved error detection. */
		v1 = -libc.Int32FromInt32(999)
		**(**int32)(__ccgo_up(piIdxCur)) = v1
		**(**int32)(__ccgo_up(piDataCur)) = v1
		return 0
	}
	iDb = _sqlite3SchemaToIndex(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, (*TTable)(unsafe.Pointer(pTab)).FpSchema)
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	if iBase < 0 {
		iBase = (*TParse)(unsafe.Pointer(pParse)).FnTab
	}
	v1 = iBase
	iBase = iBase + 1
	iDataCur = v1
	**(**int32)(__ccgo_up(piDataCur)) = iDataCur
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_WithoutRowid) == uint32(0) && (aToOpen == uintptr(0) || **(**Tu8)(__ccgo_up(aToOpen)) != 0) {
		_sqlite3OpenTable(tls, pParse, iDataCur, iDb, pTab, op)
	} else {
		if libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FnoSharedCache) == 0 {
			_sqlite3TableLock(tls, pParse, iDb, (*TTable)(unsafe.Pointer(pTab)).Ftnum, libc.BoolUint8(op == int32(OP_OpenWrite)), (*TTable)(unsafe.Pointer(pTab)).FzName)
		}
	}
	**(**int32)(__ccgo_up(piIdxCur)) = iBase
	i = 0
	pIdx = (*TTable)(unsafe.Pointer(pTab)).FpIndex
	for {
		if !(pIdx != 0) {
			break
		}
		v1 = iBase
		iBase = iBase + 1
		iIdxCur = v1
		if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x3>>0)) == int32(SQLITE_IDXTYPE_PRIMARYKEY) && !((*TTable)(unsafe.Pointer(pTab)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) {
			**(**int32)(__ccgo_up(piDataCur)) = iIdxCur
			p5 = uint8(0)
		}
		if aToOpen == uintptr(0) || **(**Tu8)(__ccgo_up(aToOpen + uintptr(i+int32(1)))) != 0 {
			_sqlite3VdbeAddOp3(tls, v, op, iIdxCur, libc.Int32FromUint32((*TIndex)(unsafe.Pointer(pIdx)).Ftnum), iDb)
			_sqlite3VdbeSetP4KeyInfo(tls, pParse, pIdx)
			_sqlite3VdbeChangeP5(tls, v, uint16(p5))
		}
		goto _3
	_3:
		;
		pIdx = (*TIndex)(unsafe.Pointer(pIdx)).FpNext
		i = i + 1
	}
	if iBase > (*TParse)(unsafe.Pointer(pParse)).FnTab {
		(*TParse)(unsafe.Pointer(pParse)).FnTab = iBase
	}
	return i
}

// C documentation
//
//	/*
//	** Allocate an Expr node which joins as many as two subtrees.
//	**
//	** One or both of the subtrees can be NULL.  Return a pointer to the new
//	** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
//	** free the subtrees and return NULL.
//	*/
func _sqlite3PExpr(tls *libc.TLS, pParse uintptr, op int32, pLeft uintptr, pRight uintptr) (r uintptr) {
	var p uintptr
	_ = p
	p = _sqlite3DbMallocRawNN(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(52))
	if p != 0 {
		libc.Xmemset(tls, p, 0, uint32(52))
		(*TExpr)(unsafe.Pointer(p)).Fop = libc.Uint8FromInt32(op & int32(0xff))
		(*TExpr)(unsafe.Pointer(p)).FiAgg = int16(-int32(1))
		_sqlite3ExprAttachSubtrees(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, p, pLeft, pRight)
		_sqlite3ExprCheckHeight(tls, pParse, (*TExpr)(unsafe.Pointer(p)).FnHeight)
	} else {
		_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pLeft)
		_sqlite3ExprDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pRight)
	}
	return p
}

// C documentation
//
//	/*
//	** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
//	** do a memory allocation failure) then delete the pSelect object.
//	*/
func _sqlite3PExprAddSelect(tls *libc.TLS, pParse uintptr, pExpr uintptr, pSelect uintptr) {
	if pExpr != 0 {
		*(*uintptr)(unsafe.Pointer(pExpr + 20)) = pSelect
		**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_xIsSelect) | libc.Int32FromInt32(EP_Subquery))
		_sqlite3ExprSetHeightAndFlags(tls, pParse, pExpr)
	} else {
		_sqlite3SelectDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pSelect)
	}
}

// C documentation
//
//	/*
//	** A call to this routine tells the pager that it is not necessary to
//	** write the information on page pPg back to the disk, even though
//	** that page might be marked as dirty.  This happens, for example, when
//	** the page has been added as a leaf of the freelist and so its
//	** content no longer matters.
//	**
//	** The overlying software layer calls this routine when all of the data
//	** on the given page is unused. The pager marks the page as clean so
//	** that it does not get written to disk.
//	**
//	** Tests show that this optimization can quadruple the speed of large
//	** DELETE operations.
//	**
//	** This optimization cannot be used with a temp-file, as the page may
//	** have been dirty at the start of the transaction. In that case, if
//	** memory pressure forces page pPg out of the cache, the data does need
//	** to be written out to disk so that it may be read back in if the
//	** current transaction is rolled back.
//	*/
func _sqlite3PagerDontWrite(tls *libc.TLS, pPg uintptr) {
	var pPager, v1 uintptr
	_, _ = pPager, v1
	pPager = (*TPgHdr)(unsafe.Pointer(pPg)).FpPager
	if !((*TPager)(unsafe.Pointer(pPager)).FtempFile != 0) && libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(pPg)).Fflags)&int32(PGHDR_DIRTY) != 0 && (*TPager)(unsafe.Pointer(pPager)).FnSavepoint == 0 {
		v1 = pPg + 28
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(PGHDR_DONT_WRITE))
		v1 = pPg + 28
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(PGHDR_WRITEABLE))
	}
}

// C documentation
//
//	/*
//	** Return the approximate number of bytes of memory currently
//	** used by the pager and its associated cache.
//	*/
func _sqlite3PagerMemUsed(tls *libc.TLS, pPager uintptr) (r int32) {
	var perPageSize int32
	_ = perPageSize
	perPageSize = int32((*TPager)(unsafe.Pointer(pPager)).FpageSize + libc.Int64FromUint16((*TPager)(unsafe.Pointer(pPager)).FnExtra) + int64(libc.Int32FromUint32(libc.Uint32FromInt64(48)+libc.Uint32FromInt32(5)*libc.Uint32FromInt64(4))))
	return int32(int64(perPageSize*_sqlite3PcachePagecount(tls, (*TPager)(unsafe.Pointer(pPager)).FpPCache)+_sqlite3MallocSize(tls, pPager)) + (*TPager)(unsafe.Pointer(pPager)).FpageSize)
}

// C documentation
//
//	/*
//	** Move the page pPg to location pgno in the file.
//	**
//	** There must be no references to the page previously located at
//	** pgno (which we call pPgOld) though that page is allowed to be
//	** in cache.  If the page previously located at pgno is not already
//	** in the rollback journal, it is not put there by by this routine.
//	**
//	** References to the page pPg remain valid. Updating any
//	** meta-data associated with pPg (i.e. data stored in the nExtra bytes
//	** allocated along with the page) is the responsibility of the caller.
//	**
//	** A transaction must be active when this routine is called. It used to be
//	** required that a statement transaction was not active, but this restriction
//	** has been removed (CREATE INDEX needs to move a page when a statement
//	** transaction is active).
//	**
//	** If the fourth argument, isCommit, is non-zero, then this page is being
//	** moved as part of a database reorganization just before the transaction
//	** is being committed. In this case, it is guaranteed that the database page
//	** pPg refers to will not be written to again within this transaction.
//	**
//	** This function may return SQLITE_NOMEM or an IO error code if an error
//	** occurs. Otherwise, it returns SQLITE_OK.
//	*/
func _sqlite3PagerMovepage(tls *libc.TLS, pPager uintptr, pPg uintptr, pgno TPgno, isCommit int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var needSyncPgno, origPgno TPgno
	var pPgOld, v3 uintptr
	var rc, v1 int32
	var v2 bool
	var _ /* pPgHdr at bp+0 */ uintptr
	_, _, _, _, _, _, _ = needSyncPgno, origPgno, pPgOld, rc, v1, v2, v3 /* The page being overwritten. */
	needSyncPgno = uint32(0)                                             /* The original page number */
	/* In order to be able to rollback, an in-memory database must journal
	 ** the page we are moving from.
	 */
	if (*TPager)(unsafe.Pointer(pPager)).FtempFile != 0 {
		rc = _sqlite3PagerWrite(tls, pPg)
		if rc != 0 {
			return rc
		}
	}
	/* If the page being moved is dirty and has not been saved by the latest
	 ** savepoint, then save the current contents of the page into the
	 ** sub-journal now. This is required to handle the following scenario:
	 **
	 **   BEGIN;
	 **     <journal page X, then modify it in memory>
	 **     SAVEPOINT one;
	 **       <Move page X to location Y>
	 **     ROLLBACK TO one;
	 **
	 ** If page X were not written to the sub-journal here, it would not
	 ** be possible to restore its contents when the "ROLLBACK TO one"
	 ** statement were is processed.
	 **
	 ** subjournalPage() may need to allocate space to store pPg->pgno into
	 ** one or more savepoint bitvecs. This is the reason this function
	 ** may return SQLITE_NOMEM.
	 */
	if v2 = libc.Int32FromUint16((*TDbPage)(unsafe.Pointer(pPg)).Fflags)&int32(PGHDR_DIRTY) != 0; v2 {
		v1 = _subjournalPageIfRequired(tls, pPg)
		rc = v1
	}
	if v2 && SQLITE_OK != v1 {
		return rc
	}
	/* If the journal needs to be sync()ed before page pPg->pgno can
	 ** be written to, store pPg->pgno in local variable needSyncPgno.
	 **
	 ** If the isCommit flag is set, there is no need to remember that
	 ** the journal needs to be sync()ed before database page pPg->pgno
	 ** can be written to. The caller has already promised not to write to it.
	 */
	if libc.Int32FromUint16((*TDbPage)(unsafe.Pointer(pPg)).Fflags)&int32(PGHDR_NEED_SYNC) != 0 && !(isCommit != 0) {
		needSyncPgno = (*TDbPage)(unsafe.Pointer(pPg)).Fpgno
	}
	/* If the cache contains a page with page-number pgno, remove it
	 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
	 ** page pgno before the 'move' operation, it needs to be retained
	 ** for the page moved there.
	 */
	v3 = pPg + 28
	*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) & ^libc.Int32FromInt32(PGHDR_NEED_SYNC))
	pPgOld = _sqlite3PagerLookup(tls, pPager, pgno)
	if pPgOld != 0 {
		if (*TPgHdr)(unsafe.Pointer(pPgOld)).FnRef > int64(1) {
			_sqlite3PagerUnrefNotNull(tls, pPgOld)
			return _sqlite3CorruptError(tls, int32(66914))
		}
		v3 = pPg + 28
		*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(pPgOld)).Fflags)&libc.Int32FromInt32(PGHDR_NEED_SYNC))
		if (*TPager)(unsafe.Pointer(pPager)).FtempFile != 0 {
			/* Do not discard pages from an in-memory database since we might
			 ** need to rollback later.  Just move the page out of the way. */
			_sqlite3PcacheMove(tls, pPgOld, (*TPager)(unsafe.Pointer(pPager)).FdbSize+uint32(1))
		} else {
			_sqlite3PcacheDrop(tls, pPgOld)
		}
	}
	origPgno = (*TDbPage)(unsafe.Pointer(pPg)).Fpgno
	_sqlite3PcacheMove(tls, pPg, pgno)
	_sqlite3PcacheMakeDirty(tls, pPg)
	/* For an in-memory database, make sure the original page continues
	 ** to exist, in case the transaction needs to roll back.  Use pPgOld
	 ** as the original page since it has already been allocated.
	 */
	if (*TPager)(unsafe.Pointer(pPager)).FtempFile != 0 && pPgOld != 0 {
		_sqlite3PcacheMove(tls, pPgOld, origPgno)
		_sqlite3PagerUnrefNotNull(tls, pPgOld)
	}
	if needSyncPgno != 0 {
		rc = _sqlite3PagerGet(tls, pPager, needSyncPgno, bp, 0)
		if rc != SQLITE_OK {
			if needSyncPgno <= (*TPager)(unsafe.Pointer(pPager)).FdbOrigSize {
				_sqlite3BitvecClear(tls, (*TPager)(unsafe.Pointer(pPager)).FpInJournal, needSyncPgno, (*TPager)(unsafe.Pointer(pPager)).FpTmpSpace)
			}
			return rc
		}
		v3 = **(**uintptr)(__ccgo_up(bp)) + 28
		*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromInt32(PGHDR_NEED_SYNC))
		_sqlite3PcacheMakeDirty(tls, **(**uintptr)(__ccgo_up(bp)))
		_sqlite3PagerUnrefNotNull(tls, **(**uintptr)(__ccgo_up(bp)))
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Read the first N bytes from the beginning of the file into memory
//	** that pDest points to.
//	**
//	** If the pager was opened on a transient file (zFilename==""), or
//	** opened on a file less than N bytes in size, the output buffer is
//	** zeroed and SQLITE_OK returned. The rationale for this is that this
//	** function is used to read database headers, and a new transient or
//	** zero sized database has a header than consists entirely of zeroes.
//	**
//	** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
//	** the error code is returned to the caller and the contents of the
//	** output buffer undefined.
//	*/
func _sqlite3PagerReadFileheader(tls *libc.TLS, pPager uintptr, N int32, pDest uintptr) (r int32) {
	var rc int32
	_ = rc
	rc = SQLITE_OK
	libc.Xmemset(tls, pDest, 0, libc.Uint32FromInt32(N))
	/* This routine is only called by btree immediately after creating
	 ** the Pager object.  There has not been an opportunity to transition
	 ** to WAL mode yet.
	 */
	if (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Ffd)).FpMethods != uintptr(0) {
		rc = _sqlite3OsRead(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, pDest, N, 0)
		if rc == libc.Int32FromInt32(SQLITE_IOERR)|libc.Int32FromInt32(2)<<libc.Int32FromInt32(8) {
			rc = SQLITE_OK
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** This function is called to rollback or release (commit) a savepoint.
//	** The savepoint to release or rollback need not be the most recently
//	** created savepoint.
//	**
//	** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
//	** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
//	** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
//	** that have occurred since the specified savepoint was created.
//	**
//	** The savepoint to rollback or release is identified by parameter
//	** iSavepoint. A value of 0 means to operate on the outermost savepoint
//	** (the first created). A value of (Pager.nSavepoint-1) means operate
//	** on the most recently created savepoint. If iSavepoint is greater than
//	** (Pager.nSavepoint-1), then this function is a no-op.
//	**
//	** If a negative value is passed to this function, then the current
//	** transaction is rolled back. This is different to calling
//	** sqlite3PagerRollback() because this function does not terminate
//	** the transaction or unlock the database, it just restores the
//	** contents of the database to its original state.
//	**
//	** In any case, all savepoints with an index greater than iSavepoint
//	** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
//	** then savepoint iSavepoint is also destroyed.
//	**
//	** This function may return SQLITE_NOMEM if a memory allocation fails,
//	** or an IO error code if an IO error occurs while rolling back a
//	** savepoint. If no errors occur, SQLITE_OK is returned.
//	*/
func _sqlite3PagerSavepoint(tls *libc.TLS, pPager uintptr, op int32, iSavepoint int32) (r int32) {
	var ii, nNew, rc, v1 int32
	var pRel, pSavepoint, v3 uintptr
	var sz Ti64
	_, _, _, _, _, _, _, _ = ii, nNew, pRel, pSavepoint, rc, sz, v1, v3
	rc = (*TPager)(unsafe.Pointer(pPager)).FerrCode
	if rc == SQLITE_OK && iSavepoint < (*TPager)(unsafe.Pointer(pPager)).FnSavepoint { /* Number of remaining savepoints after this op. */
		/* Figure out how many savepoints will still be active after this
		 ** operation. Store this value in nNew. Then free resources associated
		 ** with any savepoints that are destroyed by this operation.
		 */
		if op == int32(SAVEPOINT_RELEASE) {
			v1 = 0
		} else {
			v1 = int32(1)
		}
		nNew = iSavepoint + v1
		ii = nNew
		for {
			if !(ii < (*TPager)(unsafe.Pointer(pPager)).FnSavepoint) {
				break
			}
			_sqlite3BitvecDestroy(tls, (**(**TPagerSavepoint)(__ccgo_up((*TPager)(unsafe.Pointer(pPager)).FaSavepoint + uintptr(ii)*48))).FpInSavepoint)
			goto _2
		_2:
			;
			ii = ii + 1
		}
		(*TPager)(unsafe.Pointer(pPager)).FnSavepoint = nNew
		/* Truncate the sub-journal so that it only includes the parts
		 ** that are still in use. */
		if op == int32(SAVEPOINT_RELEASE) {
			pRel = (*TPager)(unsafe.Pointer(pPager)).FaSavepoint + uintptr(nNew)*48
			if (*TPagerSavepoint)(unsafe.Pointer(pRel)).FbTruncateOnRelease != 0 && (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Fsjfd)).FpMethods != uintptr(0) {
				/* Only truncate if it is an in-memory sub-journal. */
				if _sqlite3JournalIsInMemory(tls, (*TPager)(unsafe.Pointer(pPager)).Fsjfd) != 0 {
					sz = ((*TPager)(unsafe.Pointer(pPager)).FpageSize + int64(4)) * libc.Int64FromUint32((*TPagerSavepoint)(unsafe.Pointer(pRel)).FiSubRec)
					rc = _sqlite3OsTruncate(tls, (*TPager)(unsafe.Pointer(pPager)).Fsjfd, sz)
				}
				(*TPager)(unsafe.Pointer(pPager)).FnSubRec = (*TPagerSavepoint)(unsafe.Pointer(pRel)).FiSubRec
			}
		} else {
			if (*TPager)(unsafe.Pointer(pPager)).FpWal != uintptr(0) || (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Fjfd)).FpMethods != uintptr(0) {
				if nNew == 0 {
					v3 = uintptr(0)
				} else {
					v3 = (*TPager)(unsafe.Pointer(pPager)).FaSavepoint + uintptr(nNew-int32(1))*48
				}
				pSavepoint = v3
				rc = _pagerPlaybackSavepoint(tls, pPager, pSavepoint)
			}
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Adjust settings of the pager to those specified in the pgFlags parameter.
//	**
//	** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
//	** of the database to damage due to OS crashes or power failures by
//	** changing the number of syncs()s when writing the journals.
//	** There are four levels:
//	**
//	**    OFF       sqlite3OsSync() is never called.  This is the default
//	**              for temporary and transient files.
//	**
//	**    NORMAL    The journal is synced once before writes begin on the
//	**              database.  This is normally adequate protection, but
//	**              it is theoretically possible, though very unlikely,
//	**              that an inopertune power failure could leave the journal
//	**              in a state which would cause damage to the database
//	**              when it is rolled back.
//	**
//	**    FULL      The journal is synced twice before writes begin on the
//	**              database (with some additional information - the nRec field
//	**              of the journal header - being written in between the two
//	**              syncs).  If we assume that writing a
//	**              single disk sector is atomic, then this mode provides
//	**              assurance that the journal will not be corrupted to the
//	**              point of causing damage to the database during rollback.
//	**
//	**    EXTRA     This is like FULL except that is also syncs the directory
//	**              that contains the rollback journal after the rollback
//	**              journal is unlinked.
//	**
//	** The above is for a rollback-journal mode.  For WAL mode, OFF continues
//	** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
//	** prior to the start of checkpoint and that the database file is synced
//	** at the conclusion of the checkpoint if the entire content of the WAL
//	** was written back into the database.  But no sync operations occur for
//	** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
//	** file is synced following each commit operation, in addition to the
//	** syncs associated with NORMAL.  There is no difference between FULL
//	** and EXTRA for WAL mode.
//	**
//	** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
//	** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
//	** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
//	** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
//	** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
//	** synchronous=FULL versus synchronous=NORMAL setting determines when
//	** the xSync primitive is called and is relevant to all platforms.
//	**
//	** Numeric values associated with these states are OFF==1, NORMAL=2,
//	** and FULL=3.
//	*/
func _sqlite3PagerSetFlags(tls *libc.TLS, pPager uintptr, pgFlags uint32) {
	var level uint32
	var v1 int32
	var v2 uintptr
	_, _, _ = level, v1, v2
	level = pgFlags & uint32(PAGER_SYNCHRONOUS_MASK)
	if (*TPager)(unsafe.Pointer(pPager)).FtempFile != 0 || level == uint32(PAGER_SYNCHRONOUS_OFF) {
		(*TPager)(unsafe.Pointer(pPager)).FnoSync = uint8(1)
		(*TPager)(unsafe.Pointer(pPager)).FfullSync = uint8(0)
		(*TPager)(unsafe.Pointer(pPager)).FextraSync = uint8(0)
	} else {
		(*TPager)(unsafe.Pointer(pPager)).FnoSync = uint8(0)
		if level >= uint32(PAGER_SYNCHRONOUS_FULL) {
			v1 = int32(1)
		} else {
			v1 = 0
		}
		(*TPager)(unsafe.Pointer(pPager)).FfullSync = libc.Uint8FromInt32(v1)
		/* Set Pager.extraSync if "PRAGMA synchronous=EXTRA" is requested, or
		 ** if the file-system supports F2FS style atomic writes. If this flag
		 ** is set, SQLite syncs the directory to disk immediately after deleting
		 ** a journal file in "PRAGMA journal_mode=DELETE" mode.  */
		if level == uint32(PAGER_SYNCHRONOUS_EXTRA) {
			(*TPager)(unsafe.Pointer(pPager)).FextraSync = uint8(1)
		} else {
			(*TPager)(unsafe.Pointer(pPager)).FextraSync = uint8(0)
		}
	}
	if (*TPager)(unsafe.Pointer(pPager)).FnoSync != 0 {
		(*TPager)(unsafe.Pointer(pPager)).FsyncFlags = uint8(0)
	} else {
		if pgFlags&uint32(PAGER_FULLFSYNC) != 0 {
			(*TPager)(unsafe.Pointer(pPager)).FsyncFlags = uint8(SQLITE_SYNC_FULL)
		} else {
			(*TPager)(unsafe.Pointer(pPager)).FsyncFlags = uint8(SQLITE_SYNC_NORMAL)
		}
	}
	(*TPager)(unsafe.Pointer(pPager)).FwalSyncFlags = libc.Uint8FromInt32(libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FsyncFlags) << libc.Int32FromInt32(2))
	if (*TPager)(unsafe.Pointer(pPager)).FfullSync != 0 {
		v2 = pPager + 11
		*(*Tu8)(unsafe.Pointer(v2)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v2))) | libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FsyncFlags))
	}
	if pgFlags&uint32(PAGER_CKPT_FULLFSYNC) != 0 && !((*TPager)(unsafe.Pointer(pPager)).FnoSync != 0) {
		v2 = pPager + 11
		*(*Tu8)(unsafe.Pointer(v2)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v2))) | libc.Int32FromInt32(SQLITE_SYNC_FULL)<<libc.Int32FromInt32(2))
	}
	if pgFlags&uint32(PAGER_CACHESPILL) != 0 {
		v2 = pPager + 21
		*(*Tu8)(unsafe.Pointer(v2)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v2))) & ^libc.Int32FromInt32(SPILLFLAG_OFF))
	} else {
		v2 = pPager + 21
		*(*Tu8)(unsafe.Pointer(v2)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v2))) | libc.Int32FromInt32(SPILLFLAG_OFF))
	}
}

/*
** The following global variable is incremented whenever the library
** attempts to open a temporary file.  This information is used for
** testing and analysis only.
 */

// C documentation
//
//	/*
//	** Change the page size used by the Pager object. The new page size
//	** is passed in *pPageSize.
//	**
//	** If the pager is in the error state when this function is called, it
//	** is a no-op. The value returned is the error state error code (i.e.
//	** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
//	**
//	** Otherwise, if all of the following are true:
//	**
//	**   * the new page size (value of *pPageSize) is valid (a power
//	**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
//	**
//	**   * there are no outstanding page references, and
//	**
//	**   * the database is either not an in-memory database or it is
//	**     an in-memory database that currently consists of zero pages.
//	**
//	** then the pager object page size is set to *pPageSize.
//	**
//	** If the page size is changed, then this function uses sqlite3PagerMalloc()
//	** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
//	** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
//	** In all other cases, SQLITE_OK is returned.
//	**
//	** If the page size is not changed, either because one of the enumerated
//	** conditions above is not true, the pager was in error state when this
//	** function was called, or because the memory allocation attempt failed,
//	** then *pPageSize is set to the old, retained page size before returning.
//	*/
func _sqlite3PagerSetPagesize(tls *libc.TLS, pPager uintptr, pPageSize uintptr, nReserve int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pNew uintptr
	var pageSize Tu32
	var rc int32
	var _ /* nByte at bp+0 */ Ti64
	_, _, _ = pNew, pageSize, rc
	rc = SQLITE_OK
	/* It is not possible to do a full assert_pager_state() here, as this
	 ** function may be called from within PagerOpen(), before the state
	 ** of the Pager object is internally consistent.
	 **
	 ** At one point this function returned an error if the pager was in
	 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
	 ** there is at least one outstanding page reference, this function
	 ** is a no-op for that case anyhow.
	 */
	pageSize = **(**Tu32)(__ccgo_up(pPageSize))
	if (libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FmemDb) == 0 || (*TPager)(unsafe.Pointer(pPager)).FdbSize == uint32(0)) && _sqlite3PcacheRefCount(tls, (*TPager)(unsafe.Pointer(pPager)).FpPCache) == 0 && pageSize != 0 && pageSize != libc.Uint32FromInt64((*TPager)(unsafe.Pointer(pPager)).FpageSize) {
		pNew = libc.UintptrFromInt32(0) /* New temp space */
		**(**Ti64)(__ccgo_up(bp)) = 0
		if libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FeState) > PAGER_OPEN && (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Ffd)).FpMethods != uintptr(0) {
			rc = _sqlite3OsFileSize(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd, bp)
		}
		if rc == SQLITE_OK {
			/* 8 bytes of zeroed overrun space is sufficient so that the b-tree
			 * cell header parser will never run off the end of the allocation */
			pNew = _sqlite3PageMalloc(tls, libc.Int32FromUint32(pageSize+uint32(8)))
			if !(pNew != 0) {
				rc = int32(SQLITE_NOMEM)
			} else {
				libc.Xmemset(tls, pNew+uintptr(pageSize), 0, uint32(8))
			}
		}
		if rc == SQLITE_OK {
			_pager_reset(tls, pPager)
			rc = _sqlite3PcacheSetPageSize(tls, (*TPager)(unsafe.Pointer(pPager)).FpPCache, libc.Int32FromUint32(pageSize))
		}
		if rc == SQLITE_OK {
			_sqlite3PageFree(tls, (*TPager)(unsafe.Pointer(pPager)).FpTmpSpace)
			(*TPager)(unsafe.Pointer(pPager)).FpTmpSpace = pNew
			(*TPager)(unsafe.Pointer(pPager)).FdbSize = libc.Uint32FromInt64((**(**Ti64)(__ccgo_up(bp)) + libc.Int64FromUint32(pageSize) - libc.Int64FromInt32(1)) / libc.Int64FromUint32(pageSize))
			(*TPager)(unsafe.Pointer(pPager)).FpageSize = libc.Int64FromUint32(pageSize)
			(*TPager)(unsafe.Pointer(pPager)).FlckPgno = libc.Uint32FromInt32(_sqlite3PendingByte)/pageSize + uint32(1)
		} else {
			_sqlite3PageFree(tls, pNew)
		}
	}
	**(**Tu32)(__ccgo_up(pPageSize)) = libc.Uint32FromInt64((*TPager)(unsafe.Pointer(pPager)).FpageSize)
	if rc == SQLITE_OK {
		if nReserve < 0 {
			nReserve = int32((*TPager)(unsafe.Pointer(pPager)).FnReserve)
		}
		(*TPager)(unsafe.Pointer(pPager)).FnReserve = int16(nReserve)
		_pagerFixMaplimit(tls, pPager)
	}
	return rc
}

// C documentation
//
//	/* The main parser program.
//	** The first argument is a pointer to a structure obtained from
//	** "sqlite3ParserAlloc" which describes the current state of the parser.
//	** The second argument is the major token number.  The third is
//	** the minor token.  The fourth optional argument is whatever the
//	** user wants (and specified in the grammar) and is available for
//	** use by the action routines.
//	**
//	** Inputs:
//	** <ul>
//	** <li> A pointer to the parser (an opaque structure.)
//	** <li> The major token number.
//	** <li> The minor token number.
//	** <li> An option argument of a grammar-specified type.
//	** </ul>
//	**
//	** Outputs:
//	** None.
//	*/
func _sqlite3Parser(tls *libc.TLS, yyp uintptr, yymajor int32, yyminor TToken) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pParse, yypParser uintptr
	var yyact uint16
	var yyruleno uint32
	var _ /* yyminorunion at bp+0 */ TYYMINORTYPE
	_, _, _, _ = pParse, yyact, yypParser, yyruleno /* The parser action. */
	yypParser = yyp                                 /* The parser */
	pParse = (*TyyParser)(unsafe.Pointer(yypParser)).FpParse
	yyact = (*TyyStackEntry)(unsafe.Pointer((*TyyParser)(unsafe.Pointer(yypParser)).Fyytos)).Fstateno
	for int32(1) != 0 { /* Exit by "break" */
		yyact = _yy_find_shift_action(tls, libc.Uint16FromInt32(yymajor), yyact)
		if libc.Int32FromUint16(yyact) >= int32(YY_MIN_REDUCE) {
			yyruleno = libc.Uint32FromInt32(libc.Int32FromUint16(yyact) - int32(YY_MIN_REDUCE)) /* Reduce by this rule */
			/* Check that the stack is large enough to grow by a single entry
			 ** if the RHS of the rule is empty.  This ensures that there is room
			 ** enough on the stack to push the LHS value */
			if int32(_yyRuleInfoNRhs[yyruleno]) == 0 {
				if (*TyyParser)(unsafe.Pointer(yypParser)).Fyytos >= (*TyyParser)(unsafe.Pointer(yypParser)).FyystackEnd {
					if _yyGrowStack(tls, yypParser) != 0 {
						_yyStackOverflow(tls, yypParser)
						break
					}
				}
			}
			yyact = _yy_reduce(tls, yypParser, yyruleno, yymajor, yyminor, pParse)
		} else {
			if libc.Int32FromUint16(yyact) <= int32(YY_MAX_SHIFTREDUCE) {
				_yy_shift(tls, yypParser, yyact, libc.Uint16FromInt32(yymajor), yyminor)
				break
			} else {
				if libc.Int32FromUint16(yyact) == int32(YY_ACCEPT_ACTION) {
					(*TyyParser)(unsafe.Pointer(yypParser)).Fyytos -= 12
					_yy_accept(tls, yypParser)
					return
				} else {
					*(*TToken)(unsafe.Pointer(bp)) = yyminor
					/* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
					 ** do any kind of error recovery.  Instead, simply invoke the syntax
					 ** error routine and continue going as if nothing had happened.
					 **
					 ** Applications can set this macro (for example inside %include) if
					 ** they intend to abandon the parse upon the first syntax error seen.
					 */
					_yy_syntax_error(tls, yypParser, yymajor, yyminor)
					_yy_destructor(tls, yypParser, libc.Uint16FromInt32(yymajor), bp)
					break
				}
			}
		}
	}
	return
}

// C documentation
//
//	/*
//	** Clear all secondary memory allocations from the parser
//	*/
func _sqlite3ParserFinalize(tls *libc.TLS, p uintptr) {
	var pParser, yytos uintptr
	_, _ = pParser, yytos
	pParser = p
	/* In-lined version of calling yy_pop_parser_stack() for each
	 ** element left in the stack */
	yytos = (*TyyParser)(unsafe.Pointer(pParser)).Fyytos
	for yytos > (*TyyParser)(unsafe.Pointer(pParser)).Fyystack {
		if libc.Int32FromUint16((*TyyStackEntry)(unsafe.Pointer(yytos)).Fmajor) >= int32(YY_MIN_DSTRCTR) {
			_yy_destructor(tls, pParser, (*TyyStackEntry)(unsafe.Pointer(yytos)).Fmajor, yytos+4)
		}
		yytos -= 12
	}
	if (*TyyParser)(unsafe.Pointer(pParser)).Fyystack != pParser+16 {
		_parserStackFree(tls, (*TyyParser)(unsafe.Pointer(pParser)).Fyystack, (*TyyParser)(unsafe.Pointer(pParser)).FpParse)
	}
}

/*
** Return the peak depth of the stack for a parser.
 */

/* This array of booleans keeps track of the parser statement
** coverage.  The element yycoverage[X][Y] is set when the parser
** is in state X and has a lookahead token Y.  In a well-tested
** systems, every element of this matrix should end up being set.
 */

/*
** Write into out a description of every state/lookahead combination that
**
**   (1)  has not been used by the parser, and
**   (2)  is not a syntax error.
**
** Return the number of missed state/lookahead combinations.
 */

// C documentation
//
//	/*
//	** Make sure the page is marked as dirty. If it isn't dirty already,
//	** make it so.
//	*/
func _sqlite3PcacheMakeDirty(tls *libc.TLS, p uintptr) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(p)).Fflags)&(libc.Int32FromInt32(PGHDR_CLEAN)|libc.Int32FromInt32(PGHDR_DONT_WRITE)) != 0 { /*OPTIMIZATION-IF-FALSE*/
		v1 = p + 28
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(PGHDR_DONT_WRITE))
		if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(p)).Fflags)&int32(PGHDR_CLEAN) != 0 {
			v1 = p + 28
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) ^ (libc.Int32FromInt32(PGHDR_DIRTY) | libc.Int32FromInt32(PGHDR_CLEAN)))
			_pcacheManageDirtyList(tls, p, uint8(PCACHE_DIRTYLIST_ADD))
		}
	}
}

// C documentation
//
//	/*
//	** Decrement the reference count on a page. If the page is clean and the
//	** reference count drops to 0, then it is made eligible for recycling.
//	*/
func _sqlite3PcacheRelease(tls *libc.TLS, p uintptr) {
	var v1 Ti64
	var v2 uintptr
	_, _ = v1, v2
	(*TPCache)(unsafe.Pointer((*TPgHdr)(unsafe.Pointer(p)).FpCache)).FnRefSum = (*TPCache)(unsafe.Pointer((*TPgHdr)(unsafe.Pointer(p)).FpCache)).FnRefSum - 1
	v2 = p + 32
	*(*Ti64)(unsafe.Pointer(v2)) = *(*Ti64)(unsafe.Pointer(v2)) - 1
	v1 = *(*Ti64)(unsafe.Pointer(v2))
	if v1 == 0 {
		if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(p)).Fflags)&int32(PGHDR_CLEAN) != 0 {
			_pcacheUnpin(tls, p)
		} else {
			_pcacheManageDirtyList(tls, p, uint8(PCACHE_DIRTYLIST_FRONT))
		}
	}
}

// C documentation
//
//	/*
//	** Change the page size for PCache object. The caller must ensure that there
//	** are no outstanding page references when this function is called.
//	*/
func _sqlite3PcacheSetPageSize(tls *libc.TLS, pCache uintptr, szPage int32) (r int32) {
	var pNew uintptr
	_ = pNew
	if (*TPCache)(unsafe.Pointer(pCache)).FszPage != 0 {
		pNew = (*(*func(*libc.TLS, int32, int32, int32) uintptr)(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fpcache2.FxCreate})))(tls, szPage, libc.Int32FromUint32(libc.Uint32FromInt32((*TPCache)(unsafe.Pointer(pCache)).FszExtra)+(libc.Uint32FromInt64(48)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7))), libc.Int32FromUint8((*TPCache)(unsafe.Pointer(pCache)).FbPurgeable))
		if pNew == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		(*(*func(*libc.TLS, uintptr, int32))(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fpcache2.FxCachesize})))(tls, pNew, _numberOfCachePages(tls, pCache))
		if (*TPCache)(unsafe.Pointer(pCache)).FpCache != 0 {
			(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fpcache2.FxDestroy})))(tls, (*TPCache)(unsafe.Pointer(pCache)).FpCache)
		}
		(*TPCache)(unsafe.Pointer(pCache)).FpCache = pNew
		(*TPCache)(unsafe.Pointer(pCache)).FszPage = szPage
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Drop every cache entry whose page number is greater than "pgno". The
//	** caller must ensure that there are no outstanding references to any pages
//	** other than page 1 with a page number greater than pgno.
//	**
//	** If there is a reference to page 1 and the pgno parameter passed to this
//	** function is 0, then the data area associated with page 1 is zeroed, but
//	** the page object is not dropped.
//	*/
func _sqlite3PcacheTruncate(tls *libc.TLS, pCache uintptr, pgno TPgno) {
	var p, pNext, pPage1 uintptr
	_, _, _ = p, pNext, pPage1
	if (*TPCache)(unsafe.Pointer(pCache)).FpCache != 0 {
		p = (*TPCache)(unsafe.Pointer(pCache)).FpDirty
		for {
			if !(p != 0) {
				break
			}
			pNext = (*TPgHdr)(unsafe.Pointer(p)).FpDirtyNext
			/* This routine never gets call with a positive pgno except right
			 ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
			 ** it must be that pgno==0.
			 */
			if (*TPgHdr)(unsafe.Pointer(p)).Fpgno > pgno {
				_sqlite3PcacheMakeClean(tls, p)
			}
			goto _1
		_1:
			;
			p = pNext
		}
		if pgno == uint32(0) && (*TPCache)(unsafe.Pointer(pCache)).FnRefSum != 0 {
			pPage1 = (*(*func(*libc.TLS, uintptr, uint32, int32) uintptr)(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fpcache2.FxFetch})))(tls, (*TPCache)(unsafe.Pointer(pCache)).FpCache, uint32(1), 0)
			if pPage1 != 0 { /* Page 1 is always available in cache, because
				 ** pCache->nRefSum>0 */
				libc.Xmemset(tls, (*Tsqlite3_pcache_page)(unsafe.Pointer(pPage1)).FpBuf, 0, libc.Uint32FromInt32((*TPCache)(unsafe.Pointer(pCache)).FszPage))
				pgno = uint32(1)
			}
		}
		(*(*func(*libc.TLS, uintptr, uint32))(unsafe.Pointer(&struct{ uintptr }{_sqlite3Config.Fpcache2.FxTruncate})))(tls, (*TPCache)(unsafe.Pointer(pCache)).FpCache, pgno+uint32(1))
	}
}

// C documentation
//
//	/*
//	** If pExpr has a byte offset for the start of a token, record that as
//	** as the error offset.
//	*/
func _sqlite3RecordErrorOffsetOfExpr(tls *libc.TLS, db uintptr, pExpr uintptr) {
	for pExpr != 0 && ((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON)) != uint32(0) || *(*int32)(unsafe.Pointer(pExpr + 36)) <= 0) {
		pExpr = (*TExpr)(unsafe.Pointer(pExpr)).FpLeft
	}
	if pExpr == uintptr(0) {
		return
	}
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_FromDDL)) != uint32(0) {
		return
	}
	(*Tsqlite3)(unsafe.Pointer(db)).FerrByteOffset = *(*int32)(unsafe.Pointer(pExpr + 36))
}

// C documentation
//
//	/*
//	** Generate code that will erase and refill index *pIdx.  This is
//	** used to initialize a newly created index or to recompute the
//	** content of an index in response to a REINDEX command.
//	**
//	** if memRootPage is not negative, it means that the index is newly
//	** created.  The register specified by memRootPage contains the
//	** root page number of the index.  If memRootPage is negative, then
//	** the index already exists and must be cleared before being refilled and
//	** the root page number of the index is taken from pIndex->tnum.
//	*/
func _sqlite3RefillIndex(tls *libc.TLS, pParse uintptr, pIndex uintptr, memRootPage int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var addr1, addr2, iDb, iIdx, iSorter, iTab, j2, regRecord, v1, v3 int32
	var db, pKey, pTab, v, v2, v4 uintptr
	var tnum TPgno
	var _ /* iPartIdxLabel at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addr1, addr2, db, iDb, iIdx, iSorter, iTab, j2, pKey, pTab, regRecord, tnum, v, v1, v2, v3, v4
	pTab = (*TIndex)(unsafe.Pointer(pIndex)).FpTable
	v2 = pParse + 44
	v1 = *(*int32)(unsafe.Pointer(v2))
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1 /* The table that is indexed */
	iTab = v1
	v4 = pParse + 44
	v3 = *(*int32)(unsafe.Pointer(v4))
	*(*int32)(unsafe.Pointer(v4)) = *(*int32)(unsafe.Pointer(v4)) + 1 /* Btree cursor used for pTab */
	iIdx = v3                                                         /* Register holding assembled index record */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb                        /* The database connection */
	iDb = _sqlite3SchemaToIndex(tls, db, (*TIndex)(unsafe.Pointer(pIndex)).FpSchema)
	if _sqlite3AuthCheck(tls, pParse, int32(SQLITE_REINDEX), (*TIndex)(unsafe.Pointer(pIndex)).FzName, uintptr(0), (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName) != 0 {
		return
	}
	/* Require a write-lock on the table to perform this operation */
	_sqlite3TableLock(tls, pParse, iDb, (*TTable)(unsafe.Pointer(pTab)).Ftnum, uint8(1), (*TTable)(unsafe.Pointer(pTab)).FzName)
	v = _sqlite3GetVdbe(tls, pParse)
	if v == uintptr(0) {
		return
	}
	if memRootPage >= 0 {
		tnum = libc.Uint32FromInt32(memRootPage)
	} else {
		tnum = (*TIndex)(unsafe.Pointer(pIndex)).Ftnum
	}
	pKey = _sqlite3KeyInfoOfIndex(tls, pParse, pIndex)
	/* Open the sorter cursor if we are to use one. */
	v2 = pParse + 44
	v1 = *(*int32)(unsafe.Pointer(v2))
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	iSorter = v1
	_sqlite3VdbeAddOp4(tls, v, int32(OP_SorterOpen), iSorter, 0, libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnKeyCol), _sqlite3KeyInfoRef(tls, pKey), -int32(9))
	/* Open the table. Loop through all rows of the table, inserting index
	 ** records into the sorter. */
	_sqlite3OpenTable(tls, pParse, iTab, iDb, pTab, int32(OP_OpenRead))
	addr1 = _sqlite3VdbeAddOp2(tls, v, int32(OP_Rewind), iTab, 0)
	regRecord = _sqlite3GetTempReg(tls, pParse)
	_sqlite3MultiWrite(tls, pParse)
	_sqlite3GenerateIndexKey(tls, pParse, pIndex, iTab, regRecord, 0, bp, uintptr(0), 0)
	_sqlite3VdbeAddOp2(tls, v, int32(OP_SorterInsert), iSorter, regRecord)
	_sqlite3ResolvePartIdxLabel(tls, pParse, **(**int32)(__ccgo_up(bp)))
	_sqlite3VdbeAddOp2(tls, v, int32(OP_Next), iTab, addr1+int32(1))
	_sqlite3VdbeJumpHere(tls, v, addr1)
	if memRootPage < 0 {
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Clear), libc.Int32FromUint32(tnum), iDb)
	}
	_sqlite3VdbeAddOp4(tls, v, int32(OP_OpenWrite), iIdx, libc.Int32FromUint32(tnum), iDb, pKey, -int32(9))
	if memRootPage >= 0 {
		v1 = int32(OPFLAG_P2ISREG)
	} else {
		v1 = 0
	}
	_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(int32(OPFLAG_BULKCSR)|v1))
	addr1 = _sqlite3VdbeAddOp2(tls, v, int32(OP_SorterSort), iSorter, 0)
	if libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pIndex)).FonError) != OE_None {
		j2 = _sqlite3VdbeGoto(tls, v, int32(1))
		addr2 = _sqlite3VdbeCurrentAddr(tls, v)
		_sqlite3VdbeAddOp4Int(tls, v, int32(OP_SorterCompare), iSorter, j2, regRecord, libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIndex)).FnKeyCol))
		_sqlite3UniqueConstraint(tls, pParse, int32(OE_Abort), pIndex)
		_sqlite3VdbeJumpHere(tls, v, j2)
	} else {
		/* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
		 ** abort. The exception is if one of the indexed expressions contains a
		 ** user function that throws an exception when it is evaluated. But the
		 ** overhead of adding a statement journal to a CREATE INDEX statement is
		 ** very small (since most of the pages written do not contain content that
		 ** needs to be restored if the statement aborts), so we call
		 ** sqlite3MayAbort() for all CREATE INDEX statements.  */
		_sqlite3MayAbort(tls, pParse)
		addr2 = _sqlite3VdbeCurrentAddr(tls, v)
	}
	_sqlite3VdbeAddOp3(tls, v, int32(OP_SorterData), iSorter, regRecord, iIdx)
	if !(int32(uint32(*(*uint16)(unsafe.Pointer(pIndex + 56))&0x200>>9)) != 0) {
		/* This OP_SeekEnd opcode makes index insert for a REINDEX go much
		 ** faster by avoiding unnecessary seeks.  But the optimization does
		 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
		 ** with DESC primary keys, since those indexes have there keys in
		 ** a different order from the main table.
		 ** See ticket: https://sqlite.org/src/info/bba7b69f9849b5bf
		 */
		_sqlite3VdbeAddOp1(tls, v, int32(OP_SeekEnd), iIdx)
	}
	_sqlite3VdbeAddOp2(tls, v, int32(OP_IdxInsert), iIdx, regRecord)
	_sqlite3VdbeChangeP5(tls, v, uint16(OPFLAG_USESEEKRESULT))
	_sqlite3ReleaseTempReg(tls, pParse, regRecord)
	_sqlite3VdbeAddOp2(tls, v, int32(OP_SorterNext), iSorter, addr2)
	_sqlite3VdbeJumpHere(tls, v, addr1)
	_sqlite3VdbeAddOp1(tls, v, int32(OP_Close), iTab)
	_sqlite3VdbeAddOp1(tls, v, int32(OP_Close), iIdx)
	_sqlite3VdbeAddOp1(tls, v, int32(OP_Close), iSorter)
}

// C documentation
//
//	/*
//	** All of the FuncDef structures in the aBuiltinFunc[] array above
//	** to the global function hash table.  This occurs at start-time (as
//	** a consequence of calling sqlite3_initialize()).
//	**
//	** After this routine runs
//	*/
func _sqlite3RegisterBuiltinFunctions(tls *libc.TLS) {
	_sqlite3AlterFunctions(tls)
	_sqlite3WindowFunctions(tls)
	_sqlite3RegisterDateTimeFunctions(tls)
	_sqlite3RegisterJsonFunctions(tls)
	_sqlite3InsertBuiltinFuncs(tls, uintptr(unsafe.Pointer(&_aBuiltinFunc)), libc.Int32FromUint32(libc.Uint32FromInt64(4240)/libc.Uint32FromInt64(40)))
}

// C documentation
//
//	/*
//	** This function registered all of the above C functions as SQL
//	** functions.  This should be the only routine in this file with
//	** external linkage.
//	*/
func _sqlite3RegisterDateTimeFunctions(tls *libc.TLS) {
	_sqlite3InsertBuiltinFuncs(tls, uintptr(unsafe.Pointer(&_aDateTimeFuncs)), libc.Int32FromUint32(libc.Uint32FromInt64(400)/libc.Uint32FromInt64(40)))
}

// C documentation
//
//	/*
//	** Register JSON functions.
//	*/
func _sqlite3RegisterJsonFunctions(tls *libc.TLS) {
	_sqlite3InsertBuiltinFuncs(tls, uintptr(unsafe.Pointer(&_aJsonFunc)), libc.Int32FromUint32(libc.Uint32FromInt64(1440)/libc.Uint32FromInt64(40)))
}

// C documentation
//
//	/*
//	** Deallocate a register, making available for reuse for some other
//	** purpose.
//	*/
func _sqlite3ReleaseTempReg(tls *libc.TLS, pParse uintptr, iReg int32) {
	var v1 Tu8
	var v2 uintptr
	_, _ = v1, v2
	if iReg != 0 {
		if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FnTempReg) < libc.Int32FromUint32(libc.Uint32FromInt64(32)/libc.Uint32FromInt64(4)) {
			v2 = pParse + 19
			v1 = *(*Tu8)(unsafe.Pointer(v2))
			*(*Tu8)(unsafe.Pointer(v2)) = *(*Tu8)(unsafe.Pointer(v2)) + 1
			**(**int32)(__ccgo_up(pParse + 136 + uintptr(v1)*4)) = iReg
		}
	}
}

// C documentation
//
//	/*
//	** Remember that the parser tree element pPtr was created using
//	** the token pToken.
//	**
//	** In other words, construct a new RenameToken object and add it
//	** to the list of RenameToken objects currently being built up
//	** in pParse->pRename.
//	**
//	** The pPtr argument is returned so that this routine can be used
//	** with tail recursion in tokenExpr() routine, for a small performance
//	** improvement.
//	*/
func _sqlite3RenameTokenMap(tls *libc.TLS, pParse uintptr, pPtr uintptr, pToken uintptr) (r uintptr) {
	var pNew uintptr
	_ = pNew
	if libc.Int32FromUint8((*TParse)(unsafe.Pointer(pParse)).FeParseMode) != int32(PARSE_MODE_UNMAP) {
		pNew = _sqlite3DbMallocZero(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(16))
		if pNew != 0 {
			(*TRenameToken)(unsafe.Pointer(pNew)).Fp = pPtr
			(*TRenameToken)(unsafe.Pointer(pNew)).Ft = **(**TToken)(__ccgo_up(pToken))
			(*TRenameToken)(unsafe.Pointer(pNew)).FpNext = (*TParse)(unsafe.Pointer(pParse)).FpRename
			(*TParse)(unsafe.Pointer(pParse)).FpRename = pNew
		}
	}
	return pPtr
}

// C documentation
//
//	/*
//	** Erase all schema information from all attached databases (including
//	** "main" and "temp") for a single database connection.
//	*/
func _sqlite3ResetAllSchemasOfConnection(tls *libc.TLS, db uintptr) {
	var i int32
	var pDb, v2 uintptr
	_, _, _ = i, pDb, v2
	_sqlite3BtreeEnterAll(tls, db)
	i = 0
	for {
		if !(i < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
			break
		}
		pDb = (*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(i)*16
		if (*TDb)(unsafe.Pointer(pDb)).FpSchema != 0 {
			if (*Tsqlite3)(unsafe.Pointer(db)).FnSchemaLock == uint32(0) {
				_sqlite3SchemaClear(tls, (*TDb)(unsafe.Pointer(pDb)).FpSchema)
			} else {
				v2 = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(i)*16))).FpSchema + 78
				*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(DB_ResetWanted))
			}
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	**(**Tu32)(__ccgo_up(db + 24)) &= libc.Uint32FromInt32(^(libc.Int32FromInt32(DBFLAG_SchemaChange) | libc.Int32FromInt32(DBFLAG_SchemaKnownOk)))
	_sqlite3VtabUnlockList(tls, db)
	_sqlite3BtreeLeaveAll(tls, db)
	if (*Tsqlite3)(unsafe.Pointer(db)).FnSchemaLock == uint32(0) {
		_sqlite3CollapseDatabaseArray(tls, db)
	}
}

// C documentation
//
//	/*
//	** Reset the schema for the database at index iDb.  Also reset the
//	** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
//	** Deferred resets may be run by calling with iDb<0.
//	*/
func _sqlite3ResetOneSchema(tls *libc.TLS, db uintptr, iDb int32) {
	var i int32
	var v1 uintptr
	_, _ = i, v1
	if iDb >= 0 {
		v1 = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FpSchema + 78
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(DB_ResetWanted))
		v1 = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + 1*16))).FpSchema + 78
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(DB_ResetWanted))
		**(**Tu32)(__ccgo_up(db + 24)) &= libc.Uint32FromInt32(^libc.Int32FromInt32(DBFLAG_SchemaKnownOk))
	}
	if (*Tsqlite3)(unsafe.Pointer(db)).FnSchemaLock == uint32(0) {
		i = 0
		for {
			if !(i < (*Tsqlite3)(unsafe.Pointer(db)).FnDb) {
				break
			}
			if libc.Int32FromUint16((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(i)*16))).FpSchema)).FschemaFlags)&int32(DB_ResetWanted) == int32(DB_ResetWanted) {
				_sqlite3SchemaClear(tls, (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(i)*16))).FpSchema)
			}
			goto _3
		_3:
			;
			i = i + 1
		}
	}
}

// C documentation
//
//	/*
//	** Resolve all names for all expression in an expression list.  This is
//	** just like sqlite3ResolveExprNames() except that it works for an expression
//	** list rather than a single expression.
//	**
//	** The return value is SQLITE_OK (0) for success or SQLITE_ERROR (1) for a
//	** failure.
//	*/
func _sqlite3ResolveExprListNames(tls *libc.TLS, pNC uintptr, pList uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var i, savedHasAgg int32
	var pExpr uintptr
	var _ /* w at bp+0 */ TWalker
	_, _, _ = i, pExpr, savedHasAgg
	savedHasAgg = 0
	if pList == uintptr(0) {
		return SQLITE_OK
	}
	(**(**TWalker)(__ccgo_up(bp))).FpParse = (*TNameContext)(unsafe.Pointer(pNC)).FpParse
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_resolveExprStep)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_resolveSelectStep)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback2 = uintptr(0)
	*(*uintptr)(unsafe.Pointer(bp + 24)) = pNC
	savedHasAgg = (*TNameContext)(unsafe.Pointer(pNC)).FncFlags & (libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_MinMaxAgg) | libc.Int32FromInt32(NC_HasWin) | libc.Int32FromInt32(NC_OrderAgg))
	**(**int32)(__ccgo_up(pNC + 24)) &= ^(libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_MinMaxAgg) | libc.Int32FromInt32(NC_HasWin) | libc.Int32FromInt32(NC_OrderAgg))
	i = 0
	for {
		if !(i < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
			break
		}
		pExpr = (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FpExpr
		if pExpr == uintptr(0) {
			goto _1
		}
		**(**int32)(__ccgo_up((**(**TWalker)(__ccgo_up(bp))).FpParse + 228)) += (*TExpr)(unsafe.Pointer(pExpr)).FnHeight
		if _sqlite3ExprCheckHeight(tls, (**(**TWalker)(__ccgo_up(bp))).FpParse, (*TParse)(unsafe.Pointer((**(**TWalker)(__ccgo_up(bp))).FpParse)).FnHeight) != 0 {
			return int32(SQLITE_ERROR)
		}
		_sqlite3WalkExprNN(tls, bp, pExpr)
		**(**int32)(__ccgo_up((**(**TWalker)(__ccgo_up(bp))).FpParse + 228)) -= (*TExpr)(unsafe.Pointer(pExpr)).FnHeight
		if (*TNameContext)(unsafe.Pointer(pNC)).FncFlags&(libc.Int32FromInt32(NC_HasAgg)|libc.Int32FromInt32(NC_MinMaxAgg)|libc.Int32FromInt32(NC_HasWin)|libc.Int32FromInt32(NC_OrderAgg)) != 0 {
			**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32((*TNameContext)(unsafe.Pointer(pNC)).FncFlags & (libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_HasWin)))
			savedHasAgg = savedHasAgg | (*TNameContext)(unsafe.Pointer(pNC)).FncFlags&(libc.Int32FromInt32(NC_HasAgg)|libc.Int32FromInt32(NC_MinMaxAgg)|libc.Int32FromInt32(NC_HasWin)|libc.Int32FromInt32(NC_OrderAgg))
			**(**int32)(__ccgo_up(pNC + 24)) &= ^(libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_MinMaxAgg) | libc.Int32FromInt32(NC_HasWin) | libc.Int32FromInt32(NC_OrderAgg))
		}
		if (*TParse)(unsafe.Pointer((**(**TWalker)(__ccgo_up(bp))).FpParse)).FnErr > 0 {
			return int32(SQLITE_ERROR)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	**(**int32)(__ccgo_up(pNC + 24)) |= savedHasAgg
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This routine walks an expression tree and resolves references to
//	** table columns and result-set columns.  At the same time, do error
//	** checking on function usage and set a flag if any aggregate functions
//	** are seen.
//	**
//	** To resolve table columns references we look for nodes (or subtrees) of the
//	** form X.Y.Z or Y.Z or just Z where
//	**
//	**      X:   The name of a database.  Ex:  "main" or "temp" or
//	**           the symbolic name assigned to an ATTACH-ed database.
//	**
//	**      Y:   The name of a table in a FROM clause.  Or in a trigger
//	**           one of the special names "old" or "new".
//	**
//	**      Z:   The name of a column in table Y.
//	**
//	** The node at the root of the subtree is modified as follows:
//	**
//	**    Expr.op        Changed to TK_COLUMN
//	**    Expr.pTab      Points to the Table object for X.Y
//	**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
//	**    Expr.iTable    The VDBE cursor number for X.Y
//	**
//	**
//	** To resolve result-set references, look for expression nodes of the
//	** form Z (with no X and Y prefix) where the Z matches the right-hand
//	** size of an AS clause in the result-set of a SELECT.  The Z expression
//	** is replaced by a copy of the left-hand side of the result-set expression.
//	** Table-name and function resolution occurs on the substituted expression
//	** tree.  For example, in:
//	**
//	**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
//	**
//	** The "x" term of the order by is replaced by "a+b" to render:
//	**
//	**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
//	**
//	** Function calls are checked to make sure that the function is
//	** defined and that the correct number of arguments are specified.
//	** If the function is an aggregate function, then the NC_HasAgg flag is
//	** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
//	** If an expression contains aggregate functions then the EP_Agg
//	** property on the expression is set.
//	**
//	** An error message is left in pParse if anything is amiss.  The number
//	** if errors is returned.
//	*/
func _sqlite3ResolveExprNames(tls *libc.TLS, pNC uintptr, pExpr uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var savedHasAgg int32
	var v1 uintptr
	var _ /* w at bp+0 */ TWalker
	_, _ = savedHasAgg, v1
	if pExpr == uintptr(0) {
		return SQLITE_OK
	}
	savedHasAgg = (*TNameContext)(unsafe.Pointer(pNC)).FncFlags & (libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_MinMaxAgg) | libc.Int32FromInt32(NC_HasWin) | libc.Int32FromInt32(NC_OrderAgg))
	**(**int32)(__ccgo_up(pNC + 24)) &= ^(libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_MinMaxAgg) | libc.Int32FromInt32(NC_HasWin) | libc.Int32FromInt32(NC_OrderAgg))
	(**(**TWalker)(__ccgo_up(bp))).FpParse = (*TNameContext)(unsafe.Pointer(pNC)).FpParse
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_resolveExprStep)
	if (*TNameContext)(unsafe.Pointer(pNC)).FncFlags&int32(NC_NoSelect) != 0 {
		v1 = uintptr(0)
	} else {
		v1 = __ccgo_fp(_resolveSelectStep)
	}
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = v1
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback2 = uintptr(0)
	*(*uintptr)(unsafe.Pointer(bp + 24)) = pNC
	**(**int32)(__ccgo_up((**(**TWalker)(__ccgo_up(bp))).FpParse + 228)) += (*TExpr)(unsafe.Pointer(pExpr)).FnHeight
	if _sqlite3ExprCheckHeight(tls, (**(**TWalker)(__ccgo_up(bp))).FpParse, (*TParse)(unsafe.Pointer((**(**TWalker)(__ccgo_up(bp))).FpParse)).FnHeight) != 0 {
		return int32(SQLITE_ERROR)
	}
	_sqlite3WalkExprNN(tls, bp, pExpr)
	**(**int32)(__ccgo_up((**(**TWalker)(__ccgo_up(bp))).FpParse + 228)) -= (*TExpr)(unsafe.Pointer(pExpr)).FnHeight
	**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32((*TNameContext)(unsafe.Pointer(pNC)).FncFlags & (libc.Int32FromInt32(NC_HasAgg) | libc.Int32FromInt32(NC_HasWin)))
	**(**int32)(__ccgo_up(pNC + 24)) |= savedHasAgg
	return libc.BoolInt32((*TNameContext)(unsafe.Pointer(pNC)).FnNcErr > 0 || (*TParse)(unsafe.Pointer((**(**TWalker)(__ccgo_up(bp))).FpParse)).FnErr > 0)
}

// C documentation
//
//	/* Force the INT64 value currently stored as the result to be
//	** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL
//	** test-control.
//	*/
func _sqlite3ResultIntReal(tls *libc.TLS, pCtx uintptr) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer((*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpOut)).Fflags)&int32(MEM_Int) != 0 {
		v1 = (*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpOut + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(MEM_Int))
		v1 = (*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpOut + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_IntReal))
	}
}

// C documentation
//
//	/* If the Expr node is a subquery or an EXISTS operator or an IN operator that
//	** uses a subquery, and if the subquery is SF_Correlated, then mark the
//	** expression as EP_VarSelect.
//	*/
func _sqlite3ReturningSubqueryVarSelect(tls *libc.TLS, NotUsed uintptr, pExpr uintptr) (r int32) {
	_ = NotUsed
	if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&uint32(EP_xIsSelect) != uint32(0) && (*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FselFlags&uint32(SF_Correlated) != uint32(0) {
		**(**Tu32)(__ccgo_up(pExpr + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_VarSelect))
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Allocate a RowSet object.  Return NULL if a memory allocation
//	** error occurs.
//	*/
func _sqlite3RowSetInit(tls *libc.TLS, db uintptr) (r uintptr) {
	var N int32
	var p uintptr
	_, _ = N, p
	p = _sqlite3DbMallocRawNN(tls, db, uint64(32))
	if p != 0 {
		N = _sqlite3DbMallocSize(tls, db, p)
		(*TRowSet)(unsafe.Pointer(p)).FpChunk = uintptr(0)
		(*TRowSet)(unsafe.Pointer(p)).Fdb = db
		(*TRowSet)(unsafe.Pointer(p)).FpEntry = uintptr(0)
		(*TRowSet)(unsafe.Pointer(p)).FpLast = uintptr(0)
		(*TRowSet)(unsafe.Pointer(p)).FpForest = uintptr(0)
		(*TRowSet)(unsafe.Pointer(p)).FpFresh = uintptr((libc.Uint32FromInt64(32)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7))) + p
		(*TRowSet)(unsafe.Pointer(p)).FnFresh = uint16((libc.Uint32FromInt32(N) - (libc.Uint32FromInt64(32)+libc.Uint32FromInt32(7))&libc.Uint32FromInt32(^libc.Int32FromInt32(7))) / libc.Uint32FromInt64(16))
		(*TRowSet)(unsafe.Pointer(p)).FrsFlags = uint16(ROWSET_SORTED)
		(*TRowSet)(unsafe.Pointer(p)).FiBatch = 0
	}
	return p
}

// C documentation
//
//	/*
//	** Extract the smallest element from the RowSet.
//	** Write the element into *pRowid.  Return 1 on success.  Return
//	** 0 if the RowSet is already empty.
//	**
//	** After this routine has been called, the sqlite3RowSetInsert()
//	** routine may not be called again.
//	**
//	** This routine may not be called after sqlite3RowSetTest() has
//	** been used.  Older versions of RowSet allowed that, but as the
//	** capability was not used by the code generator, it was removed
//	** for code economy.
//	*/
func _sqlite3RowSetNext(tls *libc.TLS, p uintptr, pRowid uintptr) (r int32) {
	var v1 uintptr
	_ = v1
	/* Cannot be used with sqlite3RowSetText() */
	/* Merge the forest into a single sorted list on first call */
	if libc.Int32FromUint16((*TRowSet)(unsafe.Pointer(p)).FrsFlags)&int32(ROWSET_NEXT) == 0 { /*OPTIMIZATION-IF-FALSE*/
		if libc.Int32FromUint16((*TRowSet)(unsafe.Pointer(p)).FrsFlags)&int32(ROWSET_SORTED) == 0 { /*OPTIMIZATION-IF-FALSE*/
			(*TRowSet)(unsafe.Pointer(p)).FpEntry = _rowSetEntrySort(tls, (*TRowSet)(unsafe.Pointer(p)).FpEntry)
		}
		v1 = p + 26
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | (libc.Int32FromInt32(ROWSET_SORTED) | libc.Int32FromInt32(ROWSET_NEXT)))
	}
	/* Return the next entry on the list */
	if (*TRowSet)(unsafe.Pointer(p)).FpEntry != 0 {
		**(**Ti64)(__ccgo_up(pRowid)) = (*TRowSetEntry)(unsafe.Pointer((*TRowSet)(unsafe.Pointer(p)).FpEntry)).Fv
		(*TRowSet)(unsafe.Pointer(p)).FpEntry = (*TRowSetEntry)(unsafe.Pointer((*TRowSet)(unsafe.Pointer(p)).FpEntry)).FpRight
		if (*TRowSet)(unsafe.Pointer(p)).FpEntry == uintptr(0) { /*OPTIMIZATION-IF-TRUE*/
			/* Free memory immediately, rather than waiting on sqlite3_finalize() */
			_sqlite3RowSetClear(tls, p)
		}
		return int32(1)
	} else {
		return 0
	}
	return r
}

// C documentation
//
//	/*
//	** Check to see if element iRowid was inserted into the rowset as
//	** part of any insert batch prior to iBatch.  Return 1 or 0.
//	**
//	** If this is the first test of a new batch and if there exist entries
//	** on pRowSet->pEntry, then sort those entries into the forest at
//	** pRowSet->pForest so that they can be tested.
//	*/
func _sqlite3RowSetTest(tls *libc.TLS, pRowSet uintptr, iBatch int32, iRowid Tsqlite3_int64) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var p, pTree, ppPrevTree, v2 uintptr
	var _ /* pAux at bp+0 */ uintptr
	var _ /* pTail at bp+4 */ uintptr
	_, _, _, _ = p, pTree, ppPrevTree, v2
	/* This routine is never called after sqlite3RowSetNext() */
	/* Sort entries into the forest on the first test of a new batch.
	 ** To save unnecessary work, only do this when the batch number changes.
	 */
	if iBatch != (*TRowSet)(unsafe.Pointer(pRowSet)).FiBatch { /*OPTIMIZATION-IF-FALSE*/
		p = (*TRowSet)(unsafe.Pointer(pRowSet)).FpEntry
		if p != 0 {
			ppPrevTree = pRowSet + 20
			if libc.Int32FromUint16((*TRowSet)(unsafe.Pointer(pRowSet)).FrsFlags)&int32(ROWSET_SORTED) == 0 { /*OPTIMIZATION-IF-FALSE*/
				/* Only sort the current set of entries if they need it */
				p = _rowSetEntrySort(tls, p)
			}
			pTree = (*TRowSet)(unsafe.Pointer(pRowSet)).FpForest
			for {
				if !(pTree != 0) {
					break
				}
				ppPrevTree = pTree + 8
				if (*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft == uintptr(0) {
					(*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft = _rowSetListToTree(tls, p)
					break
				} else {
					_rowSetTreeToList(tls, (*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft, bp, bp+4)
					(*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft = uintptr(0)
					p = _rowSetEntryMerge(tls, **(**uintptr)(__ccgo_up(bp)), p)
				}
				goto _1
			_1:
				;
				pTree = (*TRowSetEntry)(unsafe.Pointer(pTree)).FpRight
			}
			if pTree == uintptr(0) {
				v2 = _rowSetEntryAlloc(tls, pRowSet)
				pTree = v2
				**(**uintptr)(__ccgo_up(ppPrevTree)) = v2
				if pTree != 0 {
					(*TRowSetEntry)(unsafe.Pointer(pTree)).Fv = 0
					(*TRowSetEntry)(unsafe.Pointer(pTree)).FpRight = uintptr(0)
					(*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft = _rowSetListToTree(tls, p)
				}
			}
			(*TRowSet)(unsafe.Pointer(pRowSet)).FpEntry = uintptr(0)
			(*TRowSet)(unsafe.Pointer(pRowSet)).FpLast = uintptr(0)
			v2 = pRowSet + 26
			*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(ROWSET_SORTED))
		}
		(*TRowSet)(unsafe.Pointer(pRowSet)).FiBatch = iBatch
	}
	/* Test to see if the iRowid value appears anywhere in the forest.
	 ** Return 1 if it does and 0 if not.
	 */
	pTree = (*TRowSet)(unsafe.Pointer(pRowSet)).FpForest
	for {
		if !(pTree != 0) {
			break
		}
		p = (*TRowSetEntry)(unsafe.Pointer(pTree)).FpLeft
		for p != 0 {
			if (*TRowSetEntry)(unsafe.Pointer(p)).Fv < iRowid {
				p = (*TRowSetEntry)(unsafe.Pointer(p)).FpRight
			} else {
				if (*TRowSetEntry)(unsafe.Pointer(p)).Fv > iRowid {
					p = (*TRowSetEntry)(unsafe.Pointer(p)).FpLeft
				} else {
					return int32(1)
				}
			}
		}
		goto _4
	_4:
		;
		pTree = (*TRowSetEntry)(unsafe.Pointer(pTree)).FpRight
	}
	return 0
}

/************** End of rowset.c **********************************************/
/************** Begin file pager.c *******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of the page cache subsystem or "pager".
**
** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
 */
/* #include "sqliteInt.h" */
/************** Include wal.h in the middle of pager.c ***********************/
/************** Begin file wal.h *********************************************/
/*
** 2010 February 1
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface to the write-ahead logging
** system. Refer to the comments below and the header comment attached to
** the implementation of each function in log.c for further details.
 */

/* #include "sqliteInt.h" */

/* Macros for extracting appropriate sync flags for either transaction
** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
 */

// C documentation
//
//	/*
//	** Find and return the schema associated with a BTree.  Create
//	** a new one if necessary.
//	*/
func _sqlite3SchemaGet(tls *libc.TLS, db uintptr, pBt uintptr) (r uintptr) {
	var p uintptr
	_ = p
	if pBt != 0 {
		p = _sqlite3BtreeSchema(tls, pBt, int32(84), __ccgo_fp(_sqlite3SchemaClear))
	} else {
		p = _sqlite3DbMallocZero(tls, uintptr(0), uint64(84))
	}
	if !(p != 0) {
		_sqlite3OomFault(tls, db)
	} else {
		if 0 == libc.Int32FromUint8((*TSchema)(unsafe.Pointer(p)).Ffile_format) {
			_sqlite3HashInit(tls, p+8)
			_sqlite3HashInit(tls, p+24)
			_sqlite3HashInit(tls, p+40)
			_sqlite3HashInit(tls, p+56)
			(*TSchema)(unsafe.Pointer(p)).Fenc = uint8(SQLITE_UTF8)
		}
	}
	return p
}

/************** End of callback.c ********************************************/
/************** Begin file delete.c ******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
 */
/* #include "sqliteInt.h" */

// C documentation
//
//	/*
//	** Check all ON clauses in pSelect to verify that they do not reference
//	** columns to the right.
//	*/
func _sqlite3SelectCheckOnClauses(tls *libc.TLS, pParse uintptr, pSelect uintptr) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var ii int32
	var pItem uintptr
	var _ /* sCtx at bp+28 */ TCheckOnCtx
	var _ /* w at bp+0 */ TWalker
	_, _ = ii, pItem
	libc.Xmemset(tls, bp, 0, uint32(28))
	(**(**TWalker)(__ccgo_up(bp))).FpParse = pParse
	(**(**TWalker)(__ccgo_up(bp))).FxExprCallback = __ccgo_fp(_selectCheckOnClausesExpr)
	(**(**TWalker)(__ccgo_up(bp))).FxSelectCallback = __ccgo_fp(_selectCheckOnClausesSelect)
	*(*uintptr)(unsafe.Pointer(bp + 24)) = bp + 28
	libc.Xmemset(tls, bp+28, 0, uint32(16))
	(**(**TCheckOnCtx)(__ccgo_up(bp + 28))).FpSrc = (*TSelect)(unsafe.Pointer(pSelect)).FpSrc
	_sqlite3WalkExpr(tls, bp, (*TSelect)(unsafe.Pointer(pSelect)).FpWhere)
	**(**Tu32)(__ccgo_up(pSelect + 4)) &= libc.Uint32FromInt32(^libc.Int32FromInt32(SF_OnToWhere))
	/* Check for any table-function args that are attached to virtual tables
	 ** on the RHS of an outer join. They are subject to the same constraints
	 ** as ON clauses. */
	(**(**TCheckOnCtx)(__ccgo_up(bp + 28))).FbFuncArg = int32(1)
	ii = 0
	for {
		if !(ii < (*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(pSelect)).FpSrc)).FnSrc) {
			break
		}
		pItem = (*TSelect)(unsafe.Pointer(pSelect)).FpSrc + 8 + uintptr(ii)*48
		if int32(*(*uint32)(unsafe.Pointer(pItem + 12 + 4))&0x8>>3) != 0 && libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pItem)).Ffg.Fjointype)&int32(JT_OUTER) != 0 {
			(**(**TCheckOnCtx)(__ccgo_up(bp + 28))).FiJoin = (*TSrcItem)(unsafe.Pointer(pItem)).FiCursor
			_sqlite3WalkExprList(tls, bp, *(*uintptr)(unsafe.Pointer(pItem + 32)))
		}
		goto _1
	_1:
		;
		ii = ii + 1
	}
}

func _sqlite3SelectDup(tls *libc.TLS, db uintptr, pDup uintptr, flags int32) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var p, pNew, pNext, pp uintptr
	var _ /* pRet at bp+0 */ uintptr
	_, _, _, _ = p, pNew, pNext, pp
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	pNext = uintptr(0)
	pp = bp
	p = pDup
	for {
		if !(p != 0) {
			break
		}
		pNew = _sqlite3DbMallocRawNN(tls, db, uint64(68))
		if pNew == uintptr(0) {
			break
		}
		(*TSelect)(unsafe.Pointer(pNew)).FpEList = _sqlite3ExprListDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpEList, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FpSrc = _sqlite3SrcListDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpSrc, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FpWhere = _sqlite3ExprDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpWhere, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FpGroupBy = _sqlite3ExprListDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpGroupBy, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FpHaving = _sqlite3ExprDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpHaving, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FpOrderBy = _sqlite3ExprListDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpOrderBy, flags)
		(*TSelect)(unsafe.Pointer(pNew)).Fop = (*TSelect)(unsafe.Pointer(p)).Fop
		(*TSelect)(unsafe.Pointer(pNew)).FpNext = pNext
		(*TSelect)(unsafe.Pointer(pNew)).FpPrior = uintptr(0)
		(*TSelect)(unsafe.Pointer(pNew)).FpLimit = _sqlite3ExprDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpLimit, flags)
		(*TSelect)(unsafe.Pointer(pNew)).FiLimit = 0
		(*TSelect)(unsafe.Pointer(pNew)).FiOffset = 0
		(*TSelect)(unsafe.Pointer(pNew)).FselFlags = (*TSelect)(unsafe.Pointer(p)).FselFlags
		(*TSelect)(unsafe.Pointer(pNew)).FnSelectRow = (*TSelect)(unsafe.Pointer(p)).FnSelectRow
		(*TSelect)(unsafe.Pointer(pNew)).FpWith = _sqlite3WithDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpWith)
		(*TSelect)(unsafe.Pointer(pNew)).FpWin = uintptr(0)
		(*TSelect)(unsafe.Pointer(pNew)).FpWinDefn = _sqlite3WindowListDup(tls, db, (*TSelect)(unsafe.Pointer(p)).FpWinDefn)
		if (*TSelect)(unsafe.Pointer(p)).FpWin != 0 && libc.Int32FromUint8((*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed) == 0 {
			_gatherSelectWindows(tls, pNew)
		}
		(*TSelect)(unsafe.Pointer(pNew)).FselId = (*TSelect)(unsafe.Pointer(p)).FselId
		if (*Tsqlite3)(unsafe.Pointer(db)).FmallocFailed != 0 {
			/* Any prior OOM might have left the Select object incomplete.
			 ** Delete the whole thing rather than allow an incomplete Select
			 ** to be used by the code generator. */
			(*TSelect)(unsafe.Pointer(pNew)).FpNext = uintptr(0)
			_sqlite3SelectDelete(tls, db, pNew)
			break
		}
		**(**uintptr)(__ccgo_up(pp)) = pNew
		pp = pNew + 44
		pNext = pNew
		goto _1
	_1:
		;
		p = (*TSelect)(unsafe.Pointer(p)).FpPrior
	}
	return **(**uintptr)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** Allocate a new Select structure and return a pointer to that
//	** structure.
//	*/
func _sqlite3SelectNew(tls *libc.TLS, pParse uintptr, pEList uintptr, pSrc uintptr, pWhere uintptr, pGroupBy uintptr, pHaving uintptr, pOrderBy uintptr, selFlags Tu32, pLimit uintptr) (r uintptr) {
	bp := tls.Alloc(80)
	defer tls.Free(80)
	var pAllocated, pNew, v1 uintptr
	var v2 int32
	var _ /* standin at bp+0 */ TSelect
	_, _, _, _ = pAllocated, pNew, v1, v2
	v1 = _sqlite3DbMallocRawNN(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(68))
	pNew = v1
	pAllocated = v1
	if pNew == uintptr(0) {
		pNew = bp
	}
	if pEList == uintptr(0) {
		pEList = _sqlite3ExprListAppend(tls, pParse, uintptr(0), _sqlite3Expr(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, int32(TK_ASTERISK), uintptr(0)))
	}
	(*TSelect)(unsafe.Pointer(pNew)).FpEList = pEList
	(*TSelect)(unsafe.Pointer(pNew)).Fop = uint8(TK_SELECT)
	(*TSelect)(unsafe.Pointer(pNew)).FselFlags = selFlags
	(*TSelect)(unsafe.Pointer(pNew)).FiLimit = 0
	(*TSelect)(unsafe.Pointer(pNew)).FiOffset = 0
	v1 = pParse + 100
	*(*int32)(unsafe.Pointer(v1)) = *(*int32)(unsafe.Pointer(v1)) + 1
	v2 = *(*int32)(unsafe.Pointer(v1))
	(*TSelect)(unsafe.Pointer(pNew)).FselId = libc.Uint32FromInt32(v2)
	(*TSelect)(unsafe.Pointer(pNew)).FnSelectRow = 0
	if pSrc == uintptr(0) {
		pSrc = _sqlite3DbMallocZero(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(uint32(libc.UintptrFromInt32(0)+8)+libc.Uint32FromInt64(48)))
	}
	(*TSelect)(unsafe.Pointer(pNew)).FpSrc = pSrc
	(*TSelect)(unsafe.Pointer(pNew)).FpWhere = pWhere
	(*TSelect)(unsafe.Pointer(pNew)).FpGroupBy = pGroupBy
	(*TSelect)(unsafe.Pointer(pNew)).FpHaving = pHaving
	(*TSelect)(unsafe.Pointer(pNew)).FpOrderBy = pOrderBy
	(*TSelect)(unsafe.Pointer(pNew)).FpPrior = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpNext = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpLimit = pLimit
	(*TSelect)(unsafe.Pointer(pNew)).FpWith = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpWin = uintptr(0)
	(*TSelect)(unsafe.Pointer(pNew)).FpWinDefn = uintptr(0)
	if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
		_clearSelect(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pNew, libc.BoolInt32(pNew != bp))
		pAllocated = uintptr(0)
	} else {
	}
	return pAllocated
}

// C documentation
//
//	/*
//	** Return true if zName is a shadow table name in the current database
//	** connection.
//	**
//	** zName is temporarily modified while this routine is running, but is
//	** restored to its original value prior to this routine returning.
//	*/
func _sqlite3ShadowTableName(tls *libc.TLS, db uintptr, zName uintptr) (r int32) {
	var pTab, zCopy, zTail, v1 uintptr
	_, _, _, _ = pTab, zCopy, zTail, v1
	zTail = libc.Xstrrchr(tls, zName, int32('_'))
	if zTail == uintptr(0) {
		return 0
	}
	zCopy = _sqlite3DbStrNDup(tls, db, zName, libc.Uint64FromInt32(int32(zTail)-int32(zName)))
	if zCopy != 0 {
		v1 = _sqlite3FindTable(tls, db, zCopy, uintptr(0))
	} else {
		v1 = uintptr(0)
	}
	pTab = v1
	_sqlite3DbFree(tls, db, zCopy)
	if pTab == uintptr(0) {
		return 0
	}
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_VTAB)) {
		return 0
	}
	return _sqlite3IsShadowTableOf(tls, db, pTab, zName)
}

// C documentation
//
//	/*
//	** Append a new table name to the given SrcList.  Create a new SrcList if
//	** need be.  A new entry is created in the SrcList even if pTable is NULL.
//	**
//	** A SrcList is returned, or NULL if there is an OOM error or if the
//	** SrcList grows to large.  The returned
//	** SrcList might be the same as the SrcList that was input or it might be
//	** a new one.  If an OOM error does occurs, then the prior value of pList
//	** that is input to this routine is automatically freed.
//	**
//	** If pDatabase is not null, it means that the table has an optional
//	** database name prefix.  Like this:  "database.table".  The pDatabase
//	** points to the table name and the pTable points to the database name.
//	** The SrcList.a[].zName field is filled with the table name which might
//	** come from pTable (if pDatabase is NULL) or from pDatabase.
//	** SrcList.a[].zDatabase is filled with the database name from pTable,
//	** or with NULL if no database is specified.
//	**
//	** In other words, if call like this:
//	**
//	**         sqlite3SrcListAppend(D,A,B,0);
//	**
//	** Then B is a table name and the database name is unspecified.  If called
//	** like this:
//	**
//	**         sqlite3SrcListAppend(D,A,B,C);
//	**
//	** Then C is the table name and B is the database name.  If C is defined
//	** then so is B.  In other words, we never have a case where:
//	**
//	**         sqlite3SrcListAppend(D,A,0,C);
//	**
//	** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
//	** before being added to the SrcList.
//	*/
func _sqlite3SrcListAppend(tls *libc.TLS, pParse uintptr, pList uintptr, pTable uintptr, pDatabase uintptr) (r uintptr) {
	var db, pItem, pNew uintptr
	_, _, _ = db, pItem, pNew
	/* Cannot have C without B */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	if pList == uintptr(0) {
		pList = _sqlite3DbMallocRawNN(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(uint32(libc.UintptrFromInt32(0)+8)+libc.Uint32FromInt32(libc.Int32FromInt32(1))*libc.Uint32FromInt64(48)))
		if pList == uintptr(0) {
			return uintptr(0)
		}
		(*TSrcList)(unsafe.Pointer(pList)).FnAlloc = uint32(1)
		(*TSrcList)(unsafe.Pointer(pList)).FnSrc = int32(1)
		libc.Xmemset(tls, pList+8, 0, uint32(48))
		(*(*TSrcItem)(unsafe.Pointer(pList + 8))).FiCursor = -int32(1)
	} else {
		pNew = _sqlite3SrcListEnlarge(tls, pParse, pList, int32(1), (*TSrcList)(unsafe.Pointer(pList)).FnSrc)
		if pNew == uintptr(0) {
			_sqlite3SrcListDelete(tls, db, pList)
			return uintptr(0)
		} else {
			pList = pNew
		}
	}
	pItem = pList + 8 + uintptr((*TSrcList)(unsafe.Pointer(pList)).FnSrc-int32(1))*48
	if pDatabase != 0 && (*TToken)(unsafe.Pointer(pDatabase)).Fz == uintptr(0) {
		pDatabase = uintptr(0)
	}
	if pDatabase != 0 {
		(*TSrcItem)(unsafe.Pointer(pItem)).FzName = _sqlite3NameFromToken(tls, db, pDatabase)
		*(*uintptr)(unsafe.Pointer(pItem + 44)) = _sqlite3NameFromToken(tls, db, pTable)
	} else {
		(*TSrcItem)(unsafe.Pointer(pItem)).FzName = _sqlite3NameFromToken(tls, db, pTable)
		*(*uintptr)(unsafe.Pointer(pItem + 44)) = uintptr(0)
	}
	return pList
}

// C documentation
//
//	/*
//	** Append the contents of SrcList p2 to SrcList p1 and return the resulting
//	** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
//	** are deleted by this function.
//	*/
func _sqlite3SrcListAppendList(tls *libc.TLS, pParse uintptr, p1 uintptr, p2 uintptr) (r uintptr) {
	var nOld int32
	var pNew, v1 uintptr
	_, _, _ = nOld, pNew, v1
	if p2 != 0 {
		nOld = (*TSrcList)(unsafe.Pointer(p1)).FnSrc
		pNew = _sqlite3SrcListEnlarge(tls, pParse, p1, (*TSrcList)(unsafe.Pointer(p2)).FnSrc, nOld)
		if pNew == uintptr(0) {
			_sqlite3SrcListDelete(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, p2)
		} else {
			p1 = pNew
			libc.Xmemcpy(tls, p1+8+uintptr(nOld)*48, p2+8, libc.Uint32FromInt32((*TSrcList)(unsafe.Pointer(p2)).FnSrc)*uint32(48))
			v1 = p1 + 8 + 12
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(JT_LTORJ)&libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(p2 + 8))).Ffg.Fjointype))
			_sqlite3DbFree(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, p2)
		}
	}
	return p1
}

// C documentation
//
//	/*
//	** If cursors, triggers, views and subqueries are all omitted from
//	** the build, then none of the following routines, except for
//	** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
//	** called with a NULL argument.
//	*/
func _sqlite3SrcListDup(tls *libc.TLS, db uintptr, p uintptr, flags int32) (r uintptr) {
	var i int32
	var pNew, pNewItem, pNewSubq, pOldItem, pTab, v3 uintptr
	var v1 Tu32
	_, _, _, _, _, _, _, _ = i, pNew, pNewItem, pNewSubq, pOldItem, pTab, v1, v3
	if p == uintptr(0) {
		return uintptr(0)
	}
	pNew = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(libc.UintptrFromInt32(0)+8)+libc.Uint32FromInt32((*TSrcList)(unsafe.Pointer(p)).FnSrc)*libc.Uint32FromInt64(48)))
	if pNew == uintptr(0) {
		return uintptr(0)
	}
	v1 = libc.Uint32FromInt32((*TSrcList)(unsafe.Pointer(p)).FnSrc)
	(*TSrcList)(unsafe.Pointer(pNew)).FnAlloc = v1
	(*TSrcList)(unsafe.Pointer(pNew)).FnSrc = libc.Int32FromUint32(v1)
	i = 0
	for {
		if !(i < (*TSrcList)(unsafe.Pointer(p)).FnSrc) {
			break
		}
		pNewItem = pNew + 8 + uintptr(i)*48
		pOldItem = p + 8 + uintptr(i)*48
		(*TSrcItem)(unsafe.Pointer(pNewItem)).Ffg = (*TSrcItem)(unsafe.Pointer(pOldItem)).Ffg
		if int32(*(*uint32)(unsafe.Pointer(pOldItem + 12 + 4))&0x4>>2) != 0 {
			pNewSubq = _sqlite3DbMallocRaw(tls, db, uint64(16))
			if pNewSubq == uintptr(0) {
				libc.SetBitFieldPtr32Uint32(pNewItem+12+4, libc.Uint32FromInt32(0), 2, 0x4)
			} else {
				libc.Xmemcpy(tls, pNewSubq, *(*uintptr)(unsafe.Pointer(pOldItem + 44)), uint32(16))
				(*TSubquery)(unsafe.Pointer(pNewSubq)).FpSelect = _sqlite3SelectDup(tls, db, (*TSubquery)(unsafe.Pointer(pNewSubq)).FpSelect, flags)
				if (*TSubquery)(unsafe.Pointer(pNewSubq)).FpSelect == uintptr(0) {
					_sqlite3DbFree(tls, db, pNewSubq)
					pNewSubq = uintptr(0)
					libc.SetBitFieldPtr32Uint32(pNewItem+12+4, libc.Uint32FromInt32(0), 2, 0x4)
				}
			}
			*(*uintptr)(unsafe.Pointer(pNewItem + 44)) = pNewSubq
		} else {
			if int32(*(*uint32)(unsafe.Pointer(pOldItem + 12 + 4))&0x10000>>16) != 0 {
				*(*uintptr)(unsafe.Pointer(pNewItem + 44)) = *(*uintptr)(unsafe.Pointer(pOldItem + 44))
			} else {
				*(*uintptr)(unsafe.Pointer(pNewItem + 44)) = _sqlite3DbStrDup(tls, db, *(*uintptr)(unsafe.Pointer(pOldItem + 44)))
			}
		}
		(*TSrcItem)(unsafe.Pointer(pNewItem)).FzName = _sqlite3DbStrDup(tls, db, (*TSrcItem)(unsafe.Pointer(pOldItem)).FzName)
		(*TSrcItem)(unsafe.Pointer(pNewItem)).FzAlias = _sqlite3DbStrDup(tls, db, (*TSrcItem)(unsafe.Pointer(pOldItem)).FzAlias)
		(*TSrcItem)(unsafe.Pointer(pNewItem)).FiCursor = (*TSrcItem)(unsafe.Pointer(pOldItem)).FiCursor
		if int32(*(*uint32)(unsafe.Pointer(pNewItem + 12 + 4))&0x2>>1) != 0 {
			*(*uintptr)(unsafe.Pointer(pNewItem + 32)) = _sqlite3DbStrDup(tls, db, *(*uintptr)(unsafe.Pointer(pOldItem + 32)))
		} else {
			if int32(*(*uint32)(unsafe.Pointer(pNewItem + 12 + 4))&0x8>>3) != 0 {
				*(*uintptr)(unsafe.Pointer(pNewItem + 32)) = _sqlite3ExprListDup(tls, db, *(*uintptr)(unsafe.Pointer(pOldItem + 32)), flags)
			} else {
				*(*Tu32)(unsafe.Pointer(pNewItem + 32)) = *(*Tu32)(unsafe.Pointer(pOldItem + 32))
			}
		}
		(*TSrcItem)(unsafe.Pointer(pNewItem)).Fu2 = (*TSrcItem)(unsafe.Pointer(pOldItem)).Fu2
		if int32(*(*uint32)(unsafe.Pointer(pNewItem + 12 + 4))&0x200>>9) != 0 {
			(*TCteUse)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pNewItem + 36)))).FnUse = (*TCteUse)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pNewItem + 36)))).FnUse + 1
		}
		v3 = (*TSrcItem)(unsafe.Pointer(pOldItem)).FpSTab
		(*TSrcItem)(unsafe.Pointer(pNewItem)).FpSTab = v3
		pTab = v3
		if pTab != 0 {
			(*TTable)(unsafe.Pointer(pTab)).FnTabRef = (*TTable)(unsafe.Pointer(pTab)).FnTabRef + 1
		}
		if int32(*(*uint32)(unsafe.Pointer(pOldItem + 12 + 4))&0x800>>11) != 0 {
			*(*uintptr)(unsafe.Pointer(pNewItem + 40)) = _sqlite3IdListDup(tls, db, *(*uintptr)(unsafe.Pointer(pOldItem + 40)))
		} else {
			*(*uintptr)(unsafe.Pointer(pNewItem + 40)) = _sqlite3ExprDup(tls, db, *(*uintptr)(unsafe.Pointer(pOldItem + 40)), flags)
		}
		(*TSrcItem)(unsafe.Pointer(pNewItem)).FcolUsed = (*TSrcItem)(unsafe.Pointer(pOldItem)).FcolUsed
		goto _2
	_2:
		;
		i = i + 1
	}
	return pNew
}

// C documentation
//
//	/*
//	** When building up a FROM clause in the parser, the join operator
//	** is initially attached to the left operand.  But the code generator
//	** expects the join operator to be on the right operand.  This routine
//	** Shifts all join operators from left to right for an entire FROM
//	** clause.
//	**
//	** Example: Suppose the join is like this:
//	**
//	**           A natural cross join B
//	**
//	** The operator is "natural cross join".  The A and B operands are stored
//	** in p->a[0] and p->a[1], respectively.  The parser initially stores the
//	** operator with A.  This routine shifts that operator over to B.
//	**
//	** Additional changes:
//	**
//	**   *   All tables to the left of the right-most RIGHT JOIN are tagged with
//	**       JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
//	**       code generator can easily tell that the table is part of
//	**       the left operand of at least one RIGHT JOIN.
//	*/
func _sqlite3SrcListShiftJoinType(tls *libc.TLS, pParse uintptr, p uintptr) {
	var allFlags, v3 Tu8
	var i, v1 int32
	var v7 uintptr
	_, _, _, _, _ = allFlags, i, v1, v3, v7
	_ = pParse
	if p != 0 && (*TSrcList)(unsafe.Pointer(p)).FnSrc > int32(1) {
		i = (*TSrcList)(unsafe.Pointer(p)).FnSrc - int32(1)
		allFlags = uint8(0)
		for {
			v3 = (*(*TSrcItem)(unsafe.Pointer(p + 8 + uintptr(i-int32(1))*48))).Ffg.Fjointype
			(*(*TSrcItem)(unsafe.Pointer(p + 8 + uintptr(i)*48))).Ffg.Fjointype = v3
			allFlags = libc.Uint8FromInt32(int32(allFlags) | libc.Int32FromUint8(v3))
			goto _2
		_2:
			;
			i = i - 1
			v1 = i
			if !(v1 > 0) {
				break
			}
		}
		(*(*TSrcItem)(unsafe.Pointer(p + 8))).Ffg.Fjointype = uint8(0)
		/* All terms to the left of a RIGHT JOIN should be tagged with the
		 ** JT_LTORJ flags */
		if libc.Int32FromUint8(allFlags)&int32(JT_RIGHT) != 0 {
			i = (*TSrcList)(unsafe.Pointer(p)).FnSrc - int32(1)
			for {
				if !(i > 0 && libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer(p + 8 + uintptr(i)*48))).Ffg.Fjointype)&int32(JT_RIGHT) == 0) {
					break
				}
				goto _4
			_4:
				;
				i = i - 1
			}
			i = i - 1
			for {
				v7 = p + 8 + uintptr(i)*48 + 12
				*(*Tu8)(unsafe.Pointer(v7)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v7))) | libc.Int32FromInt32(JT_LTORJ))
				goto _6
			_6:
				;
				i = i - 1
				v1 = i
				if !(v1 >= 0) {
					break
				}
			}
		}
	}
}

// C documentation
//
//	/*
//	** Unless it is NULL, the argument must be an UnpackedRecord object returned
//	** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
//	** the object.
//	*/
func _sqlite3Stat4ProbeFree(tls *libc.TLS, pRec uintptr) {
	var aMem, db uintptr
	var i, nCol int32
	_, _, _, _ = aMem, db, i, nCol
	if pRec != 0 {
		nCol = libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(pRec)).FpKeyInfo)).FnAllField)
		aMem = (*TUnpackedRecord)(unsafe.Pointer(pRec)).FaMem
		db = (**(**TMem)(__ccgo_up(aMem))).Fdb
		i = 0
		for {
			if !(i < nCol) {
				break
			}
			_sqlite3VdbeMemRelease(tls, aMem+uintptr(i)*40)
			goto _1
		_1:
			;
			i = i + 1
		}
		_sqlite3KeyInfoUnref(tls, (*TUnpackedRecord)(unsafe.Pointer(pRec)).FpKeyInfo)
		_sqlite3DbFreeNN(tls, db, pRec)
	}
}

func _sqlite3StatusDown(tls *libc.TLS, op int32, N int32) {
	**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4)) -= libc.Uint32FromInt32(N)
}

// C documentation
//
//	/*
//	** Adjust the highwater mark if necessary.
//	** The caller must hold the appropriate mutex.
//	*/
func _sqlite3StatusHighwater(tls *libc.TLS, op int32, X int32) {
	var newValue Tsqlite3StatValueType
	_ = newValue
	newValue = libc.Uint32FromInt32(X)
	if newValue > **(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)) {
		**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)) = newValue
	}
}

// C documentation
//
//	/*
//	** Add N to the value of a status record.  The caller must hold the
//	** appropriate mutex.  (Locking is checked by assert()).
//	**
//	** The StatusUp() routine can accept positive or negative values for N.
//	** The value of N is added to the current status value and the high-water
//	** mark is adjusted if necessary.
//	**
//	** The StatusDown() routine lowers the current value by N.  The highwater
//	** mark is unchanged.  N must be non-negative for StatusDown().
//	*/
func _sqlite3StatusUp(tls *libc.TLS, op int32, N int32) {
	**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4)) += libc.Uint32FromInt32(N)
	if **(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4)) > **(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)) {
		**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + 40 + uintptr(op)*4)) = **(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4))
	}
}

// C documentation
//
//	/*
//	** Return the current value of a status parameter.  The caller must
//	** be holding the appropriate mutex.
//	*/
func _sqlite3StatusValue(tls *libc.TLS, op int32) (r Tsqlite3_int64) {
	return libc.Int64FromUint32(**(**Tsqlite3StatValueType)(__ccgo_up(uintptr(unsafe.Pointer(&_sqlite3Stat)) + uintptr(op)*4)))
}

// C documentation
//
//	/* Convert a storage column number into a table column number.
//	**
//	** The storage column number (0,1,2,....) is the index of the value
//	** as it appears in the record on disk.  The true column number
//	** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
//	**
//	** The storage column number is less than the table column number if
//	** and only there are VIRTUAL columns to the left.
//	**
//	** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
//	*/
func _sqlite3StorageColumnToTable(tls *libc.TLS, pTab uintptr, iCol Ti16) (r Ti16) {
	var i int32
	_ = i
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_HasVirtual) != 0 {
		i = 0
		for {
			if !(i <= int32(iCol)) {
				break
			}
			if libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(i)*12))).FcolFlags)&int32(COLFLAG_VIRTUAL) != 0 {
				iCol = iCol + 1
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	return iCol
}

// C documentation
//
//	/*
//	** Enlarge the memory allocation on a StrAccum object so that it is
//	** able to accept at least N more bytes of text.
//	**
//	** Return the number of bytes of text that StrAccum is able to accept
//	** after the attempted enlargement.  The value returned might be zero.
//	*/
func _sqlite3StrAccumEnlarge(tls *libc.TLS, p uintptr, N Ti64) (r int32) {
	var szNew Ti64
	var zNew, zOld, v1 uintptr
	_, _, _, _ = szNew, zNew, zOld, v1
	/* Only called if really needed */
	if (*TStrAccum)(unsafe.Pointer(p)).FaccError != 0 {
		return 0
	}
	if (*TStrAccum)(unsafe.Pointer(p)).FmxAlloc == uint32(0) {
		_sqlite3StrAccumSetError(tls, p, uint8(SQLITE_TOOBIG))
		return libc.Int32FromUint32((*TStrAccum)(unsafe.Pointer(p)).FnAlloc - (*TStrAccum)(unsafe.Pointer(p)).FnChar - uint32(1))
	} else {
		if libc.Int32FromUint8((*TStrAccum)(unsafe.Pointer(p)).FprintfFlags)&int32(SQLITE_PRINTF_MALLOCED) != 0 {
			v1 = (*TStrAccum)(unsafe.Pointer(p)).FzText
		} else {
			v1 = uintptr(0)
		}
		zOld = v1
		szNew = libc.Int64FromUint32((*TStrAccum)(unsafe.Pointer(p)).FnChar) + N + int64(1)
		if szNew+libc.Int64FromUint32((*TStrAccum)(unsafe.Pointer(p)).FnChar) <= libc.Int64FromUint32((*TStrAccum)(unsafe.Pointer(p)).FmxAlloc) {
			/* Force exponential buffer size growth as long as it does not overflow,
			 ** to avoid having to call this routine too often */
			szNew = szNew + libc.Int64FromUint32((*TStrAccum)(unsafe.Pointer(p)).FnChar)
		}
		if szNew > libc.Int64FromUint32((*TStrAccum)(unsafe.Pointer(p)).FmxAlloc) {
			Xsqlite3_str_reset(tls, p)
			_sqlite3StrAccumSetError(tls, p, uint8(SQLITE_TOOBIG))
			return 0
		} else {
			(*TStrAccum)(unsafe.Pointer(p)).FnAlloc = libc.Uint32FromInt32(int32(szNew))
		}
		if (*TStrAccum)(unsafe.Pointer(p)).Fdb != 0 {
			zNew = _sqlite3DbRealloc(tls, (*TStrAccum)(unsafe.Pointer(p)).Fdb, zOld, uint64((*TStrAccum)(unsafe.Pointer(p)).FnAlloc))
		} else {
			zNew = _sqlite3Realloc(tls, zOld, uint64((*TStrAccum)(unsafe.Pointer(p)).FnAlloc))
		}
		if zNew != 0 {
			if !(libc.Int32FromUint8((*TStrAccum)(unsafe.Pointer(p)).FprintfFlags)&libc.Int32FromInt32(SQLITE_PRINTF_MALLOCED) != libc.Int32FromInt32(0)) && (*TStrAccum)(unsafe.Pointer(p)).FnChar > uint32(0) {
				libc.Xmemcpy(tls, zNew, (*TStrAccum)(unsafe.Pointer(p)).FzText, (*TStrAccum)(unsafe.Pointer(p)).FnChar)
			}
			(*TStrAccum)(unsafe.Pointer(p)).FzText = zNew
			(*TStrAccum)(unsafe.Pointer(p)).FnAlloc = libc.Uint32FromInt32(_sqlite3DbMallocSize(tls, (*TStrAccum)(unsafe.Pointer(p)).Fdb, zNew))
			v1 = p + 21
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(SQLITE_PRINTF_MALLOCED))
		} else {
			Xsqlite3_str_reset(tls, p)
			_sqlite3StrAccumSetError(tls, p, uint8(SQLITE_NOMEM))
			return 0
		}
	}
	return int32(N)
}

// C documentation
//
//	/*
//	** Compute a string length that is limited to what can be stored in
//	** lower 30 bits of a 32-bit signed integer.
//	**
//	** The value returned will never be negative.  Nor will it ever be greater
//	** than the actual length of the string.  For very long strings (greater
//	** than 1GiB) the value returned might be less than the true string length.
//	*/
func _sqlite3Strlen30(tls *libc.TLS, z uintptr) (r int32) {
	if z == uintptr(0) {
		return 0
	}
	return int32(0x3fffffff) & libc.Int32FromUint32(libc.Xstrlen(tls, z))
}

// C documentation
//
//	/*
//	** Make changes to the evolving bytecode to do affinity transformations
//	** of values that are about to be gathered into a row for table pTab.
//	**
//	** For ordinary (legacy, non-strict) tables:
//	** -----------------------------------------
//	**
//	** Compute the affinity string for table pTab, if it has not already been
//	** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
//	**
//	** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
//	** which were then optimized out) then this routine becomes a no-op.
//	**
//	** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
//	** affinities for register iReg and following.  Or if iReg==0,
//	** then just set the P4 operand of the previous opcode (which should  be
//	** an OP_MakeRecord) to the affinity string.
//	**
//	** A column affinity string has one character per column:
//	**
//	**    Character      Column affinity
//	**    ---------      ---------------
//	**    'A'            BLOB
//	**    'B'            TEXT
//	**    'C'            NUMERIC
//	**    'D'            INTEGER
//	**    'E'            REAL
//	**
//	** For STRICT tables:
//	** ------------------
//	**
//	** Generate an appropriate OP_TypeCheck opcode that will verify the
//	** datatypes against the column definitions in pTab.  If iReg==0, that
//	** means an OP_MakeRecord opcode has already been generated and should be
//	** the last opcode generated.  The new OP_TypeCheck needs to be inserted
//	** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
//	** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
//	** the first of a series of registers that will form the new record.
//	** Apply the type checking to that array of registers.
//	*/
func _sqlite3TableAffinity(tls *libc.TLS, v uintptr, pTab uintptr, iReg int32) {
	var i, p3 int32
	var pPrev, zColAff uintptr
	_, _, _, _ = i, p3, pPrev, zColAff
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_Strict) != 0 {
		if iReg == 0 {
			_sqlite3VdbeAppendP4(tls, v, pTab, -int32(5))
			pPrev = _sqlite3VdbeGetLastOp(tls, v)
			(*TVdbeOp)(unsafe.Pointer(pPrev)).Fopcode = uint8(OP_TypeCheck)
			p3 = (*TVdbeOp)(unsafe.Pointer(pPrev)).Fp3
			(*TVdbeOp)(unsafe.Pointer(pPrev)).Fp3 = 0
			_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), (*TVdbeOp)(unsafe.Pointer(pPrev)).Fp1, (*TVdbeOp)(unsafe.Pointer(pPrev)).Fp2, p3)
		} else {
			/* Insert an isolated OP_Typecheck */
			_sqlite3VdbeAddOp2(tls, v, int32(OP_TypeCheck), iReg, int32((*TTable)(unsafe.Pointer(pTab)).FnNVCol))
			_sqlite3VdbeAppendP4(tls, v, pTab, -int32(5))
		}
		return
	}
	zColAff = (*TTable)(unsafe.Pointer(pTab)).FzColAff
	if zColAff == uintptr(0) {
		zColAff = _sqlite3TableAffinityStr(tls, uintptr(0), pTab)
		if !(zColAff != 0) {
			_sqlite3OomFault(tls, _sqlite3VdbeDb(tls, v))
			return
		}
		(*TTable)(unsafe.Pointer(pTab)).FzColAff = zColAff
	}
	i = libc.Int32FromUint32(libc.Xstrlen(tls, zColAff) & libc.Uint32FromInt32(0x3fffffff))
	if i != 0 {
		if iReg != 0 {
			_sqlite3VdbeAddOp4(tls, v, int32(OP_Affinity), iReg, i, 0, zColAff, i)
		} else {
			_sqlite3VdbeChangeP4(tls, v, -int32(1), zColAff, i)
		}
	}
}

// C documentation
//
//	/* Convert a table column number into a storage column number.
//	**
//	** The storage column number (0,1,2,....) is the index of the value
//	** as it appears in the record on disk.  Or, if the input column is
//	** the N-th virtual column (zero-based) then the storage number is
//	** the number of non-virtual columns in the table plus N.
//	**
//	** The true column number is the index (0,1,2,...) of the column in
//	** the CREATE TABLE statement.
//	**
//	** If the input column is a VIRTUAL column, then it should not appear
//	** in storage.  But the value sometimes is cached in registers that
//	** follow the range of registers used to construct storage.  This
//	** avoids computing the same VIRTUAL column multiple times, and provides
//	** values for use by OP_Param opcodes in triggers.  Hence, if the
//	** input column is a VIRTUAL table, put it after all the other columns.
//	**
//	** In the following, N means "normal column", S means STORED, and
//	** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
//	**
//	**        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
//	**                     -- 0 1 2 3 4 5 6 7 8
//	**
//	** Then the mapping from this function is as follows:
//	**
//	**    INPUTS:     0 1 2 3 4 5 6 7 8
//	**    OUTPUTS:    0 1 6 2 3 7 4 5 8
//	**
//	** So, in other words, this routine shifts all the virtual columns to
//	** the end.
//	**
//	** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
//	** this routine is a no-op macro.  If the pTab does not have any virtual
//	** columns, then this routine is no-op that always return iCol.  If iCol
//	** is negative (indicating the ROWID column) then this routine return iCol.
//	*/
func _sqlite3TableColumnToStorage(tls *libc.TLS, pTab uintptr, iCol Ti16) (r Ti16) {
	var i int32
	var n Ti16
	_, _ = i, n
	if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_HasVirtual) == uint32(0) || int32(iCol) < 0 {
		return iCol
	}
	i = 0
	n = libc.Int16FromInt32(0)
	for {
		if !(i < int32(iCol)) {
			break
		}
		if libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(i)*12))).FcolFlags)&int32(COLFLAG_VIRTUAL) == 0 {
			n = n + 1
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	if libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer(pTab)).FaCol + uintptr(i)*12))).FcolFlags)&int32(COLFLAG_VIRTUAL) != 0 {
		/* iCol is a virtual column itself */
		return int16(int32((*TTable)(unsafe.Pointer(pTab)).FnNVCol) + i - int32(n))
	} else {
		/* iCol is a normal or stored column */
		return n
	}
	return r
}

// C documentation
//
//	/*
//	** Triggers may access values stored in the old.* or new.* pseudo-table.
//	** This function returns a 32-bit bitmask indicating which columns of the
//	** old.* or new.* tables actually are used by triggers. This information
//	** may be used by the caller, for example, to avoid having to load the entire
//	** old.* record into memory when executing an UPDATE or DELETE command.
//	**
//	** Bit 0 of the returned mask is set if the left-most column of the
//	** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
//	** the second leftmost column value is required, and so on. If there
//	** are more than 32 columns in the table, and at least one of the columns
//	** with an index greater than 32 may be accessed, 0xffffffff is returned.
//	**
//	** It is not possible to determine if the old.rowid or new.rowid column is
//	** accessed by triggers. The caller must always assume that it is.
//	**
//	** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
//	** applies to the old.* table. If 1, the new.* table.
//	**
//	** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
//	** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
//	** included in the returned mask if the TRIGGER_BEFORE bit is set in the
//	** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
//	** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
//	*/
func _sqlite3TriggerColmask(tls *libc.TLS, pParse uintptr, pTrigger uintptr, pChanges uintptr, isNew int32, tr_tm int32, pTab uintptr, orconf int32) (r Tu32) {
	var mask Tu32
	var op, v1 int32
	var p, pPrg uintptr
	_, _, _, _, _ = mask, op, p, pPrg, v1
	if pChanges != 0 {
		v1 = int32(TK_UPDATE)
	} else {
		v1 = int32(TK_DELETE)
	}
	op = v1
	mask = uint32(0)
	if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VIEW) {
		return uint32(0xffffffff)
	}
	p = pTrigger
	for {
		if !(p != 0) {
			break
		}
		if libc.Int32FromUint8((*TTrigger)(unsafe.Pointer(p)).Fop) == op && tr_tm&libc.Int32FromUint8((*TTrigger)(unsafe.Pointer(p)).Ftr_tm) != 0 && _checkColumnOverlap(tls, (*TTrigger)(unsafe.Pointer(p)).FpColumns, pChanges) != 0 {
			if (*TTrigger)(unsafe.Pointer(p)).FbReturning != 0 {
				mask = uint32(0xffffffff)
			} else {
				pPrg = _getRowTrigger(tls, pParse, p, pTab, orconf)
				if pPrg != 0 {
					mask = mask | **(**Tu32)(__ccgo_up(pPrg + 16 + uintptr(isNew)*4))
				}
			}
		}
		goto _2
	_2:
		;
		p = (*TTrigger)(unsafe.Pointer(p)).FpNext
	}
	return mask
}

// C documentation
//
//	/*
//	** Given table pTab, return a list of all the triggers attached to
//	** the table. The list is connected by Trigger.pNext pointers.
//	**
//	** All of the triggers on pTab that are in the same database as pTab
//	** are already attached to pTab->pTrigger.  But there might be additional
//	** triggers on pTab in the TEMP schema.  This routine prepends all
//	** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
//	** and returns the combined list.
//	**
//	** To state it another way:  This routine returns a list of all triggers
//	** that fire off of pTab.  The list will include any TEMP triggers on
//	** pTab as well as the triggers lised in pTab->pTrigger.
//	*/
func _sqlite3TriggerList(tls *libc.TLS, pParse uintptr, pTab uintptr) (r uintptr) {
	var p, pList, pTmpSchema, pTrig uintptr
	_, _, _, _ = p, pList, pTmpSchema, pTrig /* Loop variable for TEMP triggers */
	pTmpSchema = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FaDb + 1*16))).FpSchema
	p = (*THash)(unsafe.Pointer(pTmpSchema + 40)).Ffirst
	pList = (*TTable)(unsafe.Pointer(pTab)).FpTrigger
	for p != 0 {
		pTrig = (*THashElem)(unsafe.Pointer(p)).Fdata
		if (*TTrigger)(unsafe.Pointer(pTrig)).FpTabSchema == (*TTable)(unsafe.Pointer(pTab)).FpSchema && (*TTrigger)(unsafe.Pointer(pTrig)).Ftable != 0 && 0 == _sqlite3StrICmp(tls, (*TTrigger)(unsafe.Pointer(pTrig)).Ftable, (*TTable)(unsafe.Pointer(pTab)).FzName) && ((*TTrigger)(unsafe.Pointer(pTrig)).FpTabSchema != pTmpSchema || (*TTrigger)(unsafe.Pointer(pTrig)).FbReturning != 0) {
			(*TTrigger)(unsafe.Pointer(pTrig)).FpNext = pList
			pList = pTrig
		} else {
			if libc.Int32FromUint8((*TTrigger)(unsafe.Pointer(pTrig)).Fop) == int32(TK_RETURNING) {
				(*TTrigger)(unsafe.Pointer(pTrig)).Ftable = (*TTable)(unsafe.Pointer(pTab)).FzName
				(*TTrigger)(unsafe.Pointer(pTrig)).FpTabSchema = (*TTable)(unsafe.Pointer(pTab)).FpSchema
				(*TTrigger)(unsafe.Pointer(pTrig)).FpNext = pList
				pList = pTrig
			}
		}
		p = (*THashElem)(unsafe.Pointer(p)).Fnext
	}
	return pList
}

// C documentation
//
//	/*
//	** zIn is a UTF-16 encoded unicode string at least nByte bytes long.
//	** Return the number of bytes in the first nChar unicode characters
//	** in pZ.  nChar must be non-negative.  Surrogate pairs count as a single
//	** character.
//	*/
func _sqlite3Utf16ByteLen(tls *libc.TLS, zIn uintptr, nByte int32, nChar int32) (r int32) {
	var c, n int32
	var z, zEnd uintptr
	_, _, _, _ = c, n, z, zEnd
	z = zIn
	zEnd = z + uintptr(nByte-int32(1))
	n = 0
	if true {
		z = z + 1
	}
	for n < nChar && z <= zEnd {
		c = libc.Int32FromUint8(**(**uint8)(__ccgo_up(z)))
		z = z + uintptr(2)
		if c >= int32(0xd8) && c < int32(0xdc) && z <= zEnd && libc.Int32FromUint8(**(**uint8)(__ccgo_up(z))) >= int32(0xdc) && libc.Int32FromUint8(**(**uint8)(__ccgo_up(z))) < int32(0xe0) {
			z = z + uintptr(2)
		}
		n = n + 1
	}
	return int32(z) - int32(zIn) - libc.BoolInt32(true)
}

// C documentation
//
//	/*
//	** Add an OP_Function or OP_PureFunc opcode.
//	**
//	** The eCallCtx argument is information (typically taken from Expr.op2)
//	** that describes the calling context of the function.  0 means a general
//	** function call.  NC_IsCheck means called by a check constraint,
//	** NC_IdxExpr means called as part of an index expression.  NC_PartIdx
//	** means in the WHERE clause of a partial index.  NC_GenCol means called
//	** while computing a generated column value.  0 is the usual case.
//	*/
func _sqlite3VdbeAddFunctionCall(tls *libc.TLS, pParse uintptr, p1 int32, p2 int32, p3 int32, nArg int32, pFunc uintptr, eCallCtx int32) (r int32) {
	var addr, v1 int32
	var pCtx, v uintptr
	_, _, _, _ = addr, pCtx, v, v1
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	pCtx = _sqlite3DbMallocRawNN(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, uint64(uint32(libc.UintptrFromInt32(0)+28)+libc.Uint32FromInt32(nArg)*libc.Uint32FromInt64(4)))
	if pCtx == uintptr(0) {
		_freeEphemeralFunction(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pFunc)
		return 0
	}
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpOut = uintptr(0)
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpFunc = pFunc
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).FpVdbe = uintptr(0)
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).FisError = 0
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).Fargc = libc.Uint16FromInt32(nArg)
	(*Tsqlite3_context)(unsafe.Pointer(pCtx)).FiOp = _sqlite3VdbeCurrentAddr(tls, v)
	if eCallCtx != 0 {
		v1 = int32(OP_PureFunc)
	} else {
		v1 = int32(OP_Function)
	}
	addr = _sqlite3VdbeAddOp4(tls, v, v1, p1, p2, p3, pCtx, -int32(16))
	_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(eCallCtx&int32(NC_SelfRef)))
	_sqlite3MayAbort(tls, pParse)
	return addr
}

func _sqlite3VdbeAddOp3(tls *libc.TLS, p uintptr, op int32, p1 int32, p2 int32, p3 int32) (r int32) {
	var i int32
	var pOp uintptr
	_, _ = i, pOp
	i = (*TVdbe)(unsafe.Pointer(p)).FnOp
	if (*TVdbe)(unsafe.Pointer(p)).FnOpAlloc <= i {
		return _growOp3(tls, p, op, p1, p2, p3)
	}
	(*TVdbe)(unsafe.Pointer(p)).FnOp = (*TVdbe)(unsafe.Pointer(p)).FnOp + 1
	pOp = (*TVdbe)(unsafe.Pointer(p)).FaOp + uintptr(i)*20
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode = libc.Uint8FromInt32(op)
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp5 = uint16(0)
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 = p1
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp2 = p2
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3 = p3
	*(*uintptr)(unsafe.Pointer(pOp + 16)) = uintptr(0)
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp4type = P4_NOTUSED
	/* Replicate this logic in sqlite3VdbeAddOp4Int()
	 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
	/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	 ** Replicate in sqlite3VdbeAddOp4Int() */
	return i
}

func _sqlite3VdbeAddOp4Int(tls *libc.TLS, p uintptr, op int32, p1 int32, p2 int32, p3 int32, p4 int32) (r int32) {
	var i int32
	var pOp uintptr
	_, _ = i, pOp
	i = (*TVdbe)(unsafe.Pointer(p)).FnOp
	if (*TVdbe)(unsafe.Pointer(p)).FnOpAlloc <= i {
		return _addOp4IntSlow(tls, p, op, p1, p2, p3, p4)
	}
	(*TVdbe)(unsafe.Pointer(p)).FnOp = (*TVdbe)(unsafe.Pointer(p)).FnOp + 1
	pOp = (*TVdbe)(unsafe.Pointer(p)).FaOp + uintptr(i)*20
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode = libc.Uint8FromInt32(op)
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp5 = uint16(0)
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 = p1
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp2 = p2
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3 = p3
	*(*int32)(unsafe.Pointer(pOp + 16)) = p4
	(*TVdbeOp)(unsafe.Pointer(pOp)).Fp4type = int8(-libc.Int32FromInt32(3))
	/* Replicate this logic in sqlite3VdbeAddOp3()
	 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
	/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	 ** Replicate in sqlite3VdbeAddOp3() */
	return i
}

// C documentation
//
//	/*
//	** If parameter iOp is less than zero, then invoke the destructor for
//	** all auxiliary data pointers currently cached by the VM passed as
//	** the first argument.
//	**
//	** Or, if iOp is greater than or equal to zero, then the destructor is
//	** only invoked for those auxiliary data pointers created by the user
//	** function invoked by the OP_Function opcode at instruction iOp of
//	** VM pVdbe, and only then if:
//	**
//	**    * the associated function parameter is the 32nd or later (counting
//	**      from left to right), or
//	**
//	**    * the corresponding bit in argument mask is clear (where the first
//	**      function parameter corresponds to bit 0 etc.).
//	*/
func _sqlite3VdbeDeleteAuxData(tls *libc.TLS, db uintptr, pp uintptr, iOp int32, mask int32) {
	var pAux uintptr
	_ = pAux
	for **(**uintptr)(__ccgo_up(pp)) != 0 {
		pAux = **(**uintptr)(__ccgo_up(pp))
		if iOp < 0 || (*TAuxData)(unsafe.Pointer(pAux)).FiAuxOp == iOp && (*TAuxData)(unsafe.Pointer(pAux)).FiAuxArg >= 0 && ((*TAuxData)(unsafe.Pointer(pAux)).FiAuxArg > int32(31) || !(libc.Uint32FromInt32(mask)&(libc.Uint32FromInt32(1)<<(*TAuxData)(unsafe.Pointer(pAux)).FiAuxArg) != 0)) {
			if (*TAuxData)(unsafe.Pointer(pAux)).FxDeleteAux != 0 {
				(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TAuxData)(unsafe.Pointer(pAux)).FxDeleteAux})))(tls, (*TAuxData)(unsafe.Pointer(pAux)).FpAux)
			}
			**(**uintptr)(__ccgo_up(pp)) = (*TAuxData)(unsafe.Pointer(pAux)).FpNextAux
			_sqlite3DbFree(tls, db, pAux)
		} else {
			pp = pAux + 16
		}
	}
}

// C documentation
//
//	/*
//	** If the last opcode is "op" and it is not a jump destination,
//	** then remove it.  Return true if and only if an opcode was removed.
//	*/
func _sqlite3VdbeDeletePriorOpcode(tls *libc.TLS, p uintptr, op Tu8) (r int32) {
	if (*TVdbe)(unsafe.Pointer(p)).FnOp > 0 && libc.Int32FromUint8((**(**TOp)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FaOp + uintptr((*TVdbe)(unsafe.Pointer(p)).FnOp-int32(1))*20))).Fopcode) == libc.Int32FromUint8(op) {
		return _sqlite3VdbeChangeToNoop(tls, p, (*TVdbe)(unsafe.Pointer(p)).FnOp-int32(1))
	} else {
		return 0
	}
	return r
}

// C documentation
//
//	/*
//	** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
//	** suitable for comparing serialized records to the unpacked record passed
//	** as the only argument.
//	*/
func _sqlite3VdbeFindCompare(tls *libc.TLS, p uintptr) (r TRecordCompare) {
	var flags int32
	_ = flags
	/* varintRecordCompareInt() and varintRecordCompareString() both assume
	 ** that the size-of-header varint that occurs at the start of each record
	 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
	 ** also assumes that it is safe to overread a buffer by at least the
	 ** maximum possible legal header size plus 8 bytes. Because there is
	 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
	 ** buffer passed to varintRecordCompareInt() this makes it convenient to
	 ** limit the size of the header to 64 bytes in cases where the first field
	 ** is an integer.
	 **
	 ** The easiest way to enforce this limit is to consider only records with
	 ** 13 fields or less. If the first field is an integer, the maximum legal
	 ** header size is (12*5 + 1 + 1) bytes.  */
	if libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).FnAllField) <= int32(13) {
		flags = libc.Int32FromUint16((**(**TMem)(__ccgo_up((*TUnpackedRecord)(unsafe.Pointer(p)).FaMem))).Fflags)
		if **(**Tu8)(__ccgo_up((*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).FaSortFlags)) != 0 {
			if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).FaSortFlags)))&int32(KEYINFO_ORDER_BIGNULL) != 0 {
				return __ccgo_fp(_sqlite3VdbeRecordCompare)
			}
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fr1 = int8(1)
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fr2 = int8(-int32(1))
		} else {
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fr1 = int8(-int32(1))
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fr2 = int8(1)
		}
		if flags&int32(MEM_Int) != 0 {
			*(*Ti64)(unsafe.Pointer(p + 8)) = *(*Ti64)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FaMem))
			return __ccgo_fp(_vdbeRecordCompareInt)
		}
		if flags&(libc.Int32FromInt32(MEM_Real)|libc.Int32FromInt32(MEM_IntReal)|libc.Int32FromInt32(MEM_Null)|libc.Int32FromInt32(MEM_Blob)) == 0 && *(*uintptr)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo + 20)) == uintptr(0) {
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fu.Fz = (**(**TMem)(__ccgo_up((*TUnpackedRecord)(unsafe.Pointer(p)).FaMem))).Fz
			(*TUnpackedRecord)(unsafe.Pointer(p)).Fn = (**(**TMem)(__ccgo_up((*TUnpackedRecord)(unsafe.Pointer(p)).FaMem))).Fn
			return __ccgo_fp(_vdbeRecordCompareString)
		}
	}
	return __ccgo_fp(_sqlite3VdbeRecordCompare)
}

// C documentation
//
//	/*
//	** This is called when the record in (*p) should be found in the index
//	** opened by cursor pCur, but was not. This may happen as part of a DELETE
//	** operation or an integrity check.
//	**
//	** One reason that an exact match was not found may be the EIIB bug - that
//	** a text-to-float conversion may have caused a real value in record (*p)
//	** to be slightly different from its counterpart on disk. This function
//	** attempts to find the right index record. If it does find the right
//	** record, it leaves *pCur pointing to it and sets (*pRes) to 0 before
//	** returning. Otherwise, (*pRes) is set to non-zero and an SQLite error
//	** code returned.
//	**
//	** The algorithm used to find the correct record is:
//	**
//	**   * Scan up to BTREE_FDK_RANGE entries either side of the current entry.
//	**     If parameter bIntegrity is false, then all fields that are indexed
//	**     expressions or virtual table columns are omitted from the comparison.
//	**     If bIntegrity is true, then small differences in real values in
//	**     such fields are overlooked, but they are not omitted from the comparison
//	**     altogether.
//	**
//	**   * If the above fails to find an entry and bIntegrity is false, search
//	**     the entire index.
//	*/
func _sqlite3VdbeFindIndexKey(tls *libc.TLS, pCur uintptr, pIdx uintptr, p uintptr, pRes uintptr, bIntegrity int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iCol, ii, nStep, rc, v2 int32
	var mask TBitmask
	var _ /* res at bp+0 */ int32
	_, _, _, _, _, _ = iCol, ii, mask, nStep, rc, v2
	nStep = 0
	**(**int32)(__ccgo_up(bp)) = int32(1)
	rc = SQLITE_OK
	ii = 0
	/* Calculate a mask based on the first 64 columns of the index. The mask
	 ** bit is set if the corresponding index field is either an expression
	 ** or a virtual column of the table.  */
	mask = uint64(0)
	ii = 0
	for {
		if libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn) < libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) {
			v2 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
		} else {
			v2 = libc.Int32FromUint32(libc.Uint32FromInt64(8) * libc.Uint32FromInt32(8))
		}
		if !(ii < v2) {
			break
		}
		iCol = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(ii)*2)))
		if iCol == -int32(2) || iCol >= 0 && libc.Int32FromUint16((**(**TColumn)(__ccgo_up((*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FaCol + uintptr(iCol)*12))).FcolFlags)&int32(COLFLAG_VIRTUAL) != 0 {
			mask = mask | libc.Uint64FromInt32(1)<<ii
		}
		goto _1
	_1:
		;
		ii = ii + 1
	}
	/* If the mask is 0 at this point, then the index contains no expressions
	 ** or virtual columns. So do not search for a match - return so that the
	 ** caller may declare the db corrupt immediately. Or, if mask is non-zero,
	 ** proceed.  */
	if mask != uint64(0) {
		/* Move the cursor back BTREE_FDK_RANGE entries. If this hits an EOF,
		 ** position the cursor at the first entry in the index and set nStep
		 ** to -1 so that the first loop below scans the entire index. Otherwise,
		 ** set nStep to BTREE_FDK_RANGE*2 so that the first loop below scans
		 ** just that many entries.  */
		ii = 0
		for {
			if !(_sqlite3BtreeEof(tls, pCur) == 0 && ii < int32(BTREE_FDK_RANGE)) {
				break
			}
			rc = _sqlite3BtreePrevious(tls, pCur, 0)
			goto _3
		_3:
			;
			ii = ii + 1
		}
		if rc == int32(SQLITE_DONE) {
			rc = _sqlite3BtreeFirst(tls, pCur, bp)
			nStep = -int32(1)
		} else {
			nStep = libc.Int32FromInt32(BTREE_FDK_RANGE) * libc.Int32FromInt32(2)
		}
		/* This loop runs at most twice to search for a key with matching PK
		 ** fields in the index. The second iteration always searches the entire
		 ** index. The first iteration searches nStep entries starting with the
		 ** current cursor entry if (nStep>=0), or the entire index if (nStep<0).  */
		for _sqlite3BtreeCursorIsValidNN(tls, pCur) != 0 {
			ii = 0
			for {
				if !(rc == SQLITE_OK && (ii < nStep || nStep < 0)) {
					break
				}
				rc = _vdbeIsMatchingIndexKey(tls, pCur, bIntegrity, mask, p, bp)
				if **(**int32)(__ccgo_up(bp)) == 0 || rc != SQLITE_OK {
					break
				}
				rc = _sqlite3BtreeNext(tls, pCur, 0)
				goto _4
			_4:
				;
				ii = ii + 1
			}
			if rc == int32(SQLITE_DONE) {
				rc = SQLITE_OK
			}
			if nStep < 0 || rc != SQLITE_OK || **(**int32)(__ccgo_up(bp)) == 0 || bIntegrity != 0 {
				break
			}
			/* The first, non-exhaustive, search failed to find an entry with
			 ** matching PK fields. So restart for an exhaustive search of the
			 ** entire index.  */
			nStep = -int32(1)
			rc = _sqlite3BtreeFirst(tls, pCur, bp)
		}
	}
	**(**int32)(__ccgo_up(pRes)) = **(**int32)(__ccgo_up(bp))
	return rc
}

func _sqlite3VdbeFreeCursorNN(tls *libc.TLS, p uintptr, pCx uintptr) {
	var pModule, pVCur uintptr
	_, _ = pModule, pVCur
	if int32(TBool(*(*uint8)(unsafe.Pointer(pCx + 8))&0x10>>4)) != 0 {
		_freeCursorWithCache(tls, p, pCx)
		return
	}
	switch libc.Int32FromUint8((*TVdbeCursor)(unsafe.Pointer(pCx)).FeCurType) {
	case int32(CURTYPE_SORTER):
		_sqlite3VdbeSorterClose(tls, (*TVdbe)(unsafe.Pointer(p)).Fdb, pCx)
	case CURTYPE_BTREE:
		_sqlite3BtreeCloseCursor(tls, *(*uintptr)(unsafe.Pointer(pCx + 36)))
	case int32(CURTYPE_VTAB):
		pVCur = *(*uintptr)(unsafe.Pointer(pCx + 36))
		pModule = (*Tsqlite3_vtab)(unsafe.Pointer((*Tsqlite3_vtab_cursor)(unsafe.Pointer(pVCur)).FpVtab)).FpModule
		(*Tsqlite3_vtab)(unsafe.Pointer((*Tsqlite3_vtab_cursor)(unsafe.Pointer(pVCur)).FpVtab)).FnRef = (*Tsqlite3_vtab)(unsafe.Pointer((*Tsqlite3_vtab_cursor)(unsafe.Pointer(pVCur)).FpVtab)).FnRef - 1
		(*(*func(*libc.TLS, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_module)(unsafe.Pointer(pModule)).FxClose})))(tls, pVCur)
		break
	}
}

// C documentation
//
//	/*
//	** Return a pointer to an sqlite3_value structure containing the value bound
//	** parameter iVar of VM v. Except, if the value is an SQL NULL, return
//	** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
//	** constants) to the value before returning it.
//	**
//	** The returned value must be freed by the caller using sqlite3ValueFree().
//	*/
func _sqlite3VdbeGetBoundValue(tls *libc.TLS, v uintptr, iVar int32, aff Tu8) (r uintptr) {
	var pMem, pRet uintptr
	_, _ = pMem, pRet
	if v != 0 {
		pMem = (*TVdbe)(unsafe.Pointer(v)).FaVar + uintptr(iVar-int32(1))*40
		if 0 == libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Null) {
			pRet = _sqlite3ValueNew(tls, (*TVdbe)(unsafe.Pointer(v)).Fdb)
			if pRet != 0 {
				_sqlite3VdbeMemCopy(tls, pRet, pMem)
				_sqlite3ValueApplyAffinity(tls, pRet, aff, uint8(SQLITE_UTF8))
			}
			return pRet
		}
	}
	return uintptr(0)
}

// C documentation
//
//	/*
//	** Compare the key of the index entry that cursor pC is pointing to against
//	** the key string in pUnpacked.  Write into *pRes a number
//	** that is negative, zero, or positive if pC is less than, equal to,
//	** or greater than pUnpacked.  Return SQLITE_OK on success.
//	**
//	** pUnpacked is either created without a rowid or is truncated so that it
//	** omits the rowid at the end.  The rowid at the end of the index entry
//	** is ignored as well.  Hence, this routine only compares the prefixes
//	** of the keys prior to the final rowid, not the entire key.
//	*/
func _sqlite3VdbeIdxKeyCompare(tls *libc.TLS, db uintptr, pC uintptr, pUnpacked uintptr, res uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var nCellKey Ti64
	var pCur uintptr
	var rc int32
	var _ /* m at bp+0 */ TMem
	_, _, _ = nCellKey, pCur, rc
	nCellKey = 0
	pCur = *(*uintptr)(unsafe.Pointer(pC + 36))
	nCellKey = libc.Int64FromUint32(_sqlite3BtreePayloadSize(tls, pCur))
	/* nCellKey will always be between 0 and 0xffffffff because of the way
	 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
	if nCellKey <= 0 || nCellKey > int64(0x7fffffff) {
		**(**int32)(__ccgo_up(res)) = 0
		return _sqlite3CorruptError(tls, int32(93164))
	}
	_sqlite3VdbeMemInit(tls, bp, db, uint16(0))
	rc = _sqlite3VdbeMemFromBtreeZeroOffset(tls, pCur, libc.Uint32FromInt64(nCellKey), bp)
	if rc != 0 {
		return rc
	}
	**(**int32)(__ccgo_up(res)) = _sqlite3VdbeRecordCompareWithSkip(tls, (**(**TMem)(__ccgo_up(bp))).Fn, (**(**TMem)(__ccgo_up(bp))).Fz, pUnpacked, 0)
	_sqlite3VdbeMemReleaseMalloc(tls, bp)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** pCur points at an index entry created using the OP_MakeRecord opcode.
//	** Read the rowid (the last field in the record) and store it in *rowid.
//	** Return SQLITE_OK if everything works, or an error code otherwise.
//	**
//	** pCur might be pointing to text obtained from a corrupt database file.
//	** So the content cannot be trusted.  Do appropriate checks on the content.
//	*/
func _sqlite3VdbeIdxRowid(tls *libc.TLS, db uintptr, pCur uintptr, rowid uintptr) (r int32) {
	bp := tls.Alloc(96)
	defer tls.Free(96)
	var lenRowid Tu32
	var nCellKey Ti64
	var rc int32
	var _ /* m at bp+8 */ TMem
	var _ /* szHdr at bp+0 */ Tu32
	var _ /* typeRowid at bp+4 */ Tu32
	var _ /* v at bp+48 */ TMem
	_, _, _ = lenRowid, nCellKey, rc
	nCellKey = 0
	/* Get the size of the index entry.  Only indices entries of less
	 ** than 2GiB are support - anything large must be database corruption.
	 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
	 ** this code can safely assume that nCellKey is 32-bits
	 */
	nCellKey = libc.Int64FromUint32(_sqlite3BtreePayloadSize(tls, pCur))
	/* Read in the complete content of the index entry */
	_sqlite3VdbeMemInit(tls, bp+8, db, uint16(0))
	rc = _sqlite3VdbeMemFromBtreeZeroOffset(tls, pCur, libc.Uint32FromInt64(nCellKey), bp+8)
	if rc != 0 {
		return rc
	}
	/* The index entry must begin with a header size */
	**(**Tu32)(__ccgo_up(bp)) = uint32(**(**Tu8)(__ccgo_up((**(**TMem)(__ccgo_up(bp + 8))).Fz)))
	if **(**Tu32)(__ccgo_up(bp)) >= uint32(0x80) {
		_sqlite3GetVarint32(tls, (**(**TMem)(__ccgo_up(bp + 8))).Fz, bp)
	}
	if **(**Tu32)(__ccgo_up(bp)) < uint32(3) || **(**Tu32)(__ccgo_up(bp)) > libc.Uint32FromInt32((**(**TMem)(__ccgo_up(bp + 8))).Fn) {
		goto idx_rowid_corruption
	}
	/* The last field of the index should be an integer - the ROWID.
	 ** Verify that the last entry really is an integer. */
	**(**Tu32)(__ccgo_up(bp + 4)) = uint32(**(**Tu8)(__ccgo_up((**(**TMem)(__ccgo_up(bp + 8))).Fz + uintptr(**(**Tu32)(__ccgo_up(bp))-uint32(1)))))
	if **(**Tu32)(__ccgo_up(bp + 4)) >= uint32(0x80) {
		_sqlite3GetVarint32(tls, (**(**TMem)(__ccgo_up(bp + 8))).Fz+uintptr(**(**Tu32)(__ccgo_up(bp))-uint32(1)), bp+4)
	}
	if **(**Tu32)(__ccgo_up(bp + 4)) < uint32(1) || **(**Tu32)(__ccgo_up(bp + 4)) > uint32(9) || **(**Tu32)(__ccgo_up(bp + 4)) == uint32(7) {
		goto idx_rowid_corruption
	}
	lenRowid = uint32(_sqlite3SmallTypeSizes[**(**Tu32)(__ccgo_up(bp + 4))])
	if libc.Uint32FromInt32((**(**TMem)(__ccgo_up(bp + 8))).Fn) < **(**Tu32)(__ccgo_up(bp))+lenRowid {
		goto idx_rowid_corruption
	}
	/* Fetch the integer off the end of the index record */
	_sqlite3VdbeSerialGet(tls, (**(**TMem)(__ccgo_up(bp + 8))).Fz+uintptr(libc.Uint32FromInt32((**(**TMem)(__ccgo_up(bp + 8))).Fn)-lenRowid), **(**Tu32)(__ccgo_up(bp + 4)), bp+48)
	**(**Ti64)(__ccgo_up(rowid)) = *(*Ti64)(unsafe.Pointer(bp + 48))
	_sqlite3VdbeMemReleaseMalloc(tls, bp+8)
	return SQLITE_OK
	/* Jump here if database corruption is detected after m has been
	 ** allocated.  Free the m object and return SQLITE_CORRUPT. */
	goto idx_rowid_corruption
idx_rowid_corruption:
	;
	_sqlite3VdbeMemReleaseMalloc(tls, bp+8)
	return _sqlite3CorruptError(tls, int32(93131))
}

// C documentation
//
//	/*
//	** Cast the datatype of the value in pMem according to the affinity
//	** "aff".  Casting is different from applying affinity in that a cast
//	** is forced.  In other words, the value is converted into the desired
//	** affinity even if that results in loss of data.  This routine is
//	** used (for example) to implement the SQL "cast()" operator.
//	*/
func _sqlite3VdbeMemCast(tls *libc.TLS, pMem uintptr, aff Tu8, encoding Tu8) (r int32) {
	var rc int32
	var v1 uintptr
	_, _ = rc, v1
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Null) != 0 {
		return SQLITE_OK
	}
	switch libc.Int32FromUint8(aff) {
	case int32(SQLITE_AFF_BLOB): /* Really a cast to BLOB */
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Blob) == 0 {
			_sqlite3ValueApplyAffinity(tls, pMem, uint8(SQLITE_AFF_TEXT), encoding)
			if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Str) != 0 {
				(*TMem)(unsafe.Pointer(pMem)).Fflags = libc.Uint16FromInt32(libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags) & ^(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Zero)) | int32(MEM_Blob))
			}
		} else {
			v1 = pMem + 16
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_TypeMask) & ^libc.Int32FromInt32(MEM_Blob)))
		}
	case int32(SQLITE_AFF_NUMERIC):
		_sqlite3VdbeMemNumerify(tls, pMem)
	case int32(SQLITE_AFF_INTEGER):
		_sqlite3VdbeMemIntegerify(tls, pMem)
	case int32(SQLITE_AFF_REAL):
		_sqlite3VdbeMemRealify(tls, pMem)
	default:
		v1 = pMem + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&libc.Int32FromInt32(MEM_Blob)>>libc.Int32FromInt32(3))
		_sqlite3ValueApplyAffinity(tls, pMem, uint8(SQLITE_AFF_TEXT), encoding)
		v1 = pMem + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Int) | libc.Int32FromInt32(MEM_Real) | libc.Int32FromInt32(MEM_IntReal) | libc.Int32FromInt32(MEM_Blob) | libc.Int32FromInt32(MEM_Zero)))
		if libc.Int32FromUint8(encoding) != int32(SQLITE_UTF8) {
			**(**int32)(__ccgo_up(pMem + 12)) &= ^libc.Int32FromInt32(1)
		}
		rc = _sqlite3VdbeChangeEncoding(tls, pMem, libc.Int32FromUint8(encoding))
		if rc != 0 {
			return rc
		}
		_sqlite3VdbeMemZeroTerminateIfAble(tls, pMem)
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Make a full copy of pFrom into pTo.  Prior contents of pTo are
//	** freed before the copy is made.
//	*/
func _sqlite3VdbeMemCopy(tls *libc.TLS, pTo uintptr, pFrom uintptr) (r int32) {
	var rc int32
	var v1 uintptr
	_, _ = rc, v1
	rc = SQLITE_OK
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pTo)).Fflags)&(libc.Int32FromInt32(MEM_Agg)|libc.Int32FromInt32(MEM_Dyn)) != 0 {
		_vdbeMemClearExternAndSetNull(tls, pTo)
	}
	libc.Xmemcpy(tls, pTo, pFrom, uint32(libc.UintptrFromInt32(0)+20))
	v1 = pTo + 16
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(MEM_Dyn))
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pTo)).Fflags)&(libc.Int32FromInt32(MEM_Str)|libc.Int32FromInt32(MEM_Blob)) != 0 {
		if 0 == libc.Int32FromUint16((*TMem)(unsafe.Pointer(pFrom)).Fflags)&int32(MEM_Static) {
			v1 = pTo + 16
			*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | libc.Int32FromInt32(MEM_Ephem))
			rc = _sqlite3VdbeMemMakeWriteable(tls, pTo)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** If the given Mem* has a zero-filled tail, turn it into an ordinary
//	** blob stored in dynamically allocated space.
//	*/
func _sqlite3VdbeMemExpandBlob(tls *libc.TLS, pMem uintptr) (r int32) {
	var nByte int32
	var v1 uintptr
	_, _ = nByte, v1
	/* Set nByte to the number of bytes required to store the expanded blob. */
	nByte = (*TMem)(unsafe.Pointer(pMem)).Fn + *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pMem)).Fu))
	if nByte <= 0 {
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Blob) == 0 {
			return SQLITE_OK
		}
		nByte = int32(1)
	}
	if _sqlite3VdbeMemGrow(tls, pMem, nByte, int32(1)) != 0 {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, (*TMem)(unsafe.Pointer(pMem)).Fz+uintptr((*TMem)(unsafe.Pointer(pMem)).Fn), 0, libc.Uint32FromInt32(*(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pMem)).Fu))))
	**(**int32)(__ccgo_up(pMem + 12)) += *(*int32)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(pMem)).Fu))
	v1 = pMem + 16
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Zero) | libc.Int32FromInt32(MEM_Term)))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Make sure pMem->z points to a writable allocation of at least n bytes.
//	**
//	** If the bPreserve argument is true, then copy of the content of
//	** pMem->z into the new allocation.  pMem must be either a string or
//	** blob if bPreserve is true.  If bPreserve is false, any prior content
//	** in pMem->z is discarded.
//	*/
func _sqlite3VdbeMemGrow(tls *libc.TLS, pMem uintptr, n int32, bPreserve int32) (r int32) {
	var v1 uintptr
	_ = v1
	/* If the bPreserve flag is set to true, then the memory cell must already
	 ** contain a valid string or blob value.  */
	if (*TMem)(unsafe.Pointer(pMem)).FszMalloc > 0 && bPreserve != 0 && (*TMem)(unsafe.Pointer(pMem)).Fz == (*TMem)(unsafe.Pointer(pMem)).FzMalloc {
		if (*TMem)(unsafe.Pointer(pMem)).Fdb != 0 {
			v1 = _sqlite3DbReallocOrFree(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, (*TMem)(unsafe.Pointer(pMem)).Fz, libc.Uint64FromInt32(n))
			(*TMem)(unsafe.Pointer(pMem)).FzMalloc = v1
			(*TMem)(unsafe.Pointer(pMem)).Fz = v1
		} else {
			(*TMem)(unsafe.Pointer(pMem)).FzMalloc = _sqlite3Realloc(tls, (*TMem)(unsafe.Pointer(pMem)).Fz, libc.Uint64FromInt32(n))
			if (*TMem)(unsafe.Pointer(pMem)).FzMalloc == uintptr(0) {
				Xsqlite3_free(tls, (*TMem)(unsafe.Pointer(pMem)).Fz)
			}
			(*TMem)(unsafe.Pointer(pMem)).Fz = (*TMem)(unsafe.Pointer(pMem)).FzMalloc
		}
		bPreserve = 0
	} else {
		if (*TMem)(unsafe.Pointer(pMem)).FszMalloc > 0 {
			_sqlite3DbFreeNN(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, (*TMem)(unsafe.Pointer(pMem)).FzMalloc)
		}
		(*TMem)(unsafe.Pointer(pMem)).FzMalloc = _sqlite3DbMallocRaw(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, libc.Uint64FromInt32(n))
	}
	if (*TMem)(unsafe.Pointer(pMem)).FzMalloc == uintptr(0) {
		_sqlite3VdbeMemSetNull(tls, pMem)
		(*TMem)(unsafe.Pointer(pMem)).Fz = uintptr(0)
		(*TMem)(unsafe.Pointer(pMem)).FszMalloc = 0
		return int32(SQLITE_NOMEM)
	} else {
		(*TMem)(unsafe.Pointer(pMem)).FszMalloc = _sqlite3DbMallocSize(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, (*TMem)(unsafe.Pointer(pMem)).FzMalloc)
	}
	if bPreserve != 0 && (*TMem)(unsafe.Pointer(pMem)).Fz != 0 {
		libc.Xmemcpy(tls, (*TMem)(unsafe.Pointer(pMem)).FzMalloc, (*TMem)(unsafe.Pointer(pMem)).Fz, libc.Uint32FromInt32((*TMem)(unsafe.Pointer(pMem)).Fn))
	}
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Dyn) != 0 {
		(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMem)(unsafe.Pointer(pMem)).FxDel})))(tls, (*TMem)(unsafe.Pointer(pMem)).Fz)
	}
	(*TMem)(unsafe.Pointer(pMem)).Fz = (*TMem)(unsafe.Pointer(pMem)).FzMalloc
	v1 = pMem + 16
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Dyn) | libc.Int32FromInt32(MEM_Ephem) | libc.Int32FromInt32(MEM_Static)))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Change pMem so that its MEM_Str or MEM_Blob value is stored in
//	** MEM.zMalloc, where it can be safely written.
//	**
//	** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
//	*/
func _sqlite3VdbeMemMakeWriteable(tls *libc.TLS, pMem uintptr) (r int32) {
	var rc, v1 int32
	var v2 uintptr
	_, _, _ = rc, v1, v2
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&(libc.Int32FromInt32(MEM_Str)|libc.Int32FromInt32(MEM_Blob)) != 0 {
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&int32(MEM_Zero) != 0 {
			v1 = _sqlite3VdbeMemExpandBlob(tls, pMem)
		} else {
			v1 = 0
		}
		if v1 != 0 {
			return int32(SQLITE_NOMEM)
		}
		if (*TMem)(unsafe.Pointer(pMem)).FszMalloc == 0 || (*TMem)(unsafe.Pointer(pMem)).Fz != (*TMem)(unsafe.Pointer(pMem)).FzMalloc {
			rc = _vdbeMemAddTerminator(tls, pMem)
			if rc != 0 {
				return rc
			}
		}
	}
	v2 = pMem + 16
	*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) & ^libc.Int32FromInt32(MEM_Ephem))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Convert pMem so that it has type MEM_Real or MEM_Int.
//	** Invalidate any prior representations.
//	**
//	** Every effort is made to force the conversion, even if the input
//	** is a string that does not look completely like a number.  Convert
//	** as much of the string as we can and ignore the rest.
//	*/
func _sqlite3VdbeMemNumerify(tls *libc.TLS, pMem uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var rc int32
	var v1 Tsqlite3_int64
	var v2 bool
	var v3 uintptr
	var _ /* ix at bp+0 */ Tsqlite3_int64
	_, _, _, _ = rc, v1, v2, v3
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&(libc.Int32FromInt32(MEM_Int)|libc.Int32FromInt32(MEM_Real)|libc.Int32FromInt32(MEM_IntReal)|libc.Int32FromInt32(MEM_Null)) == 0 {
		rc = _sqlite3MemRealValueRC(tls, pMem, pMem)
		if v2 = rc&int32(2) == 0 && _sqlite3Atoi64(tls, (*TMem)(unsafe.Pointer(pMem)).Fz, bp, (*TMem)(unsafe.Pointer(pMem)).Fn, (*TMem)(unsafe.Pointer(pMem)).Fenc) < int32(2); !v2 {
			v1 = _sqlite3RealToI64(tls, *(*float64)(unsafe.Pointer(pMem)))
			**(**Tsqlite3_int64)(__ccgo_up(bp)) = v1
		}
		if v2 || _sqlite3RealSameAsInt(tls, *(*float64)(unsafe.Pointer(pMem)), v1) != 0 {
			*(*Ti64)(unsafe.Pointer(pMem)) = **(**Tsqlite3_int64)(__ccgo_up(bp))
			(*TMem)(unsafe.Pointer(pMem)).Fflags = libc.Uint16FromInt32(libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags) & ^(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Zero)) | int32(MEM_Int))
		} else {
			(*TMem)(unsafe.Pointer(pMem)).Fflags = libc.Uint16FromInt32(libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags) & ^(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Zero)) | int32(MEM_Real))
		}
	}
	v3 = pMem + 16
	*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) & ^(libc.Int32FromInt32(MEM_Str) | libc.Int32FromInt32(MEM_Blob) | libc.Int32FromInt32(MEM_Zero)))
	return SQLITE_OK
}

func _sqlite3VdbeMemShallowCopy(tls *libc.TLS, pTo uintptr, pFrom uintptr, srcType int32) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pTo)).Fflags)&(libc.Int32FromInt32(MEM_Agg)|libc.Int32FromInt32(MEM_Dyn)) != 0 {
		_vdbeClrCopy(tls, pTo, pFrom, srcType)
		return
	}
	libc.Xmemcpy(tls, pTo, pFrom, uint32(libc.UintptrFromInt32(0)+20))
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pFrom)).Fflags)&int32(MEM_Static) == 0 {
		v1 = pTo + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Dyn) | libc.Int32FromInt32(MEM_Static) | libc.Int32FromInt32(MEM_Ephem)))
		v1 = pTo + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | srcType)
	}
}

// C documentation
//
//	/*
//	** Add MEM_Str to the set of representations for the given Mem.  This
//	** routine is only called if pMem is a number of some kind, not a NULL
//	** or a BLOB.
//	**
//	** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
//	** if bForce is true but are retained if bForce is false.
//	**
//	** A MEM_Null value will never be passed to this function. This function is
//	** used for converting values to text for returning to the user (i.e. via
//	** sqlite3_value_text()), or for ensuring that values to be used as btree
//	** keys are strings. In the former case a NULL pointer is returned the
//	** user and the latter is an internal programming error.
//	*/
func _sqlite3VdbeMemStringify(tls *libc.TLS, pMem uintptr, enc Tu8, bForce Tu8) (r int32) {
	var nByte int32
	var v1 uintptr
	_, _ = nByte, v1
	nByte = int32(32)
	if _sqlite3VdbeMemClearAndResize(tls, pMem, nByte) != 0 {
		(*TMem)(unsafe.Pointer(pMem)).Fenc = uint8(0)
		return int32(SQLITE_NOMEM)
	}
	_vdbeMemRenderNum(tls, nByte, (*TMem)(unsafe.Pointer(pMem)).Fz, pMem)
	(*TMem)(unsafe.Pointer(pMem)).Fenc = uint8(SQLITE_UTF8)
	v1 = pMem + 16
	*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) | (libc.Int32FromInt32(MEM_Str) | libc.Int32FromInt32(MEM_Term)))
	if bForce != 0 {
		v1 = pMem + 16
		*(*Tu16)(unsafe.Pointer(v1)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(MEM_Int) | libc.Int32FromInt32(MEM_Real) | libc.Int32FromInt32(MEM_IntReal)))
	}
	_sqlite3VdbeChangeEncoding(tls, pMem, libc.Int32FromUint8(enc))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This routine transforms the internal text encoding used by pMem to
//	** desiredEnc. It is an error if the string is already of the desired
//	** encoding, or if *pMem does not contain a string value.
//	*/
func _sqlite3VdbeMemTranslate(tls *libc.TLS, pMem uintptr, desiredEnc Tu8) (r int32) {
	var c uint32
	var c2, c21, rc int32
	var len1 Tsqlite3_int64
	var temp Tu8
	var z, zIn, zOut, zTerm, v1, v2 uintptr
	_, _, _, _, _, _, _, _, _, _, _, _ = c, c2, c21, len1, rc, temp, z, zIn, zOut, zTerm, v1, v2
	/* If the translation is between UTF-16 little and big endian, then
	 ** all that is required is to swap the byte order. This case is handled
	 ** differently from the others.
	 */
	if libc.Int32FromUint8((*TMem)(unsafe.Pointer(pMem)).Fenc) != int32(SQLITE_UTF8) && libc.Int32FromUint8(desiredEnc) != int32(SQLITE_UTF8) {
		rc = _sqlite3VdbeMemMakeWriteable(tls, pMem)
		if rc != SQLITE_OK {
			return int32(SQLITE_NOMEM)
		}
		zIn = (*TMem)(unsafe.Pointer(pMem)).Fz
		zTerm = zIn + uintptr((*TMem)(unsafe.Pointer(pMem)).Fn & ^libc.Int32FromInt32(1))
		for zIn < zTerm {
			temp = **(**uint8)(__ccgo_up(zIn))
			**(**uint8)(__ccgo_up(zIn)) = **(**uint8)(__ccgo_up(zIn + libc.UintptrFromInt32(1)))
			zIn = zIn + 1
			v1 = zIn
			zIn = zIn + 1
			**(**uint8)(__ccgo_up(v1)) = temp
		}
		(*TMem)(unsafe.Pointer(pMem)).Fenc = desiredEnc
		goto translate_out
	}
	/* Set len to the maximum number of bytes required in the output buffer. */
	if libc.Int32FromUint8(desiredEnc) == int32(SQLITE_UTF8) {
		/* When converting from UTF-16, the maximum growth results from
		 ** translating a 2-byte character to a 4-byte UTF-8 character.
		 ** A single byte is required for the output string
		 ** nul-terminator.
		 */
		**(**int32)(__ccgo_up(pMem + 12)) &= ^libc.Int32FromInt32(1)
		len1 = int64(2)*int64((*TMem)(unsafe.Pointer(pMem)).Fn) + int64(1)
	} else {
		/* When converting from UTF-8 to UTF-16 the maximum growth is caused
		 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
		 ** character. Two bytes are required in the output buffer for the
		 ** nul-terminator.
		 */
		len1 = int64(2)*int64((*TMem)(unsafe.Pointer(pMem)).Fn) + int64(2)
	}
	/* Set zIn to point at the start of the input buffer and zTerm to point 1
	 ** byte past the end.
	 **
	 ** Variable zOut is set to point at the output buffer, space obtained
	 ** from sqlite3_malloc().
	 */
	zIn = (*TMem)(unsafe.Pointer(pMem)).Fz
	zTerm = zIn + uintptr((*TMem)(unsafe.Pointer(pMem)).Fn)
	zOut = _sqlite3DbMallocRaw(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, libc.Uint64FromInt64(len1))
	if !(zOut != 0) {
		return int32(SQLITE_NOMEM)
	}
	z = zOut
	if libc.Int32FromUint8((*TMem)(unsafe.Pointer(pMem)).Fenc) == int32(SQLITE_UTF8) {
		if libc.Int32FromUint8(desiredEnc) == int32(SQLITE_UTF16LE) {
			/* UTF-8 -> UTF-16 Little-endian */
			for zIn < zTerm {
				v1 = zIn
				zIn = zIn + 1
				c = uint32(**(**uint8)(__ccgo_up(v1)))
				if c >= uint32(0xc0) {
					c = uint32(_sqlite3Utf8Trans1[c-uint32(0xc0)])
					for zIn < zTerm && libc.Int32FromUint8(**(**uint8)(__ccgo_up(zIn)))&int32(0xc0) == int32(0x80) {
						v1 = zIn
						zIn = zIn + 1
						c = c<<int32(6) + libc.Uint32FromInt32(libc.Int32FromInt32(0x3f)&libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))))
					}
					if c < uint32(0x80) || c&uint32(0xFFFFF800) == uint32(0xD800) || c&uint32(0xFFFFFFFE) == uint32(0xFFFE) {
						c = uint32(0xFFFD)
					}
				}
				if c <= uint32(0xFFFF) {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0x00FF))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c >> libc.Int32FromInt32(8) & libc.Uint32FromInt32(0x00FF))
				} else {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c>>libc.Int32FromInt32(10)&libc.Uint32FromInt32(0x003F) + (c-libc.Uint32FromInt32(0x10000))>>libc.Int32FromInt32(10)&libc.Uint32FromInt32(0x00C0))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(libc.Uint32FromInt32(0x00D8) + (c-libc.Uint32FromInt32(0x10000))>>libc.Int32FromInt32(18)&libc.Uint32FromInt32(0x03))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0x00FF))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(libc.Uint32FromInt32(0x00DC) + c>>libc.Int32FromInt32(8)&libc.Uint32FromInt32(0x03))
				}
			}
		} else {
			/* UTF-8 -> UTF-16 Big-endian */
			for zIn < zTerm {
				v1 = zIn
				zIn = zIn + 1
				c = uint32(**(**uint8)(__ccgo_up(v1)))
				if c >= uint32(0xc0) {
					c = uint32(_sqlite3Utf8Trans1[c-uint32(0xc0)])
					for zIn < zTerm && libc.Int32FromUint8(**(**uint8)(__ccgo_up(zIn)))&int32(0xc0) == int32(0x80) {
						v1 = zIn
						zIn = zIn + 1
						c = c<<int32(6) + libc.Uint32FromInt32(libc.Int32FromInt32(0x3f)&libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))))
					}
					if c < uint32(0x80) || c&uint32(0xFFFFF800) == uint32(0xD800) || c&uint32(0xFFFFFFFE) == uint32(0xFFFE) {
						c = uint32(0xFFFD)
					}
				}
				if c <= uint32(0xFFFF) {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c >> libc.Int32FromInt32(8) & libc.Uint32FromInt32(0x00FF))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0x00FF))
				} else {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(libc.Uint32FromInt32(0x00D8) + (c-libc.Uint32FromInt32(0x10000))>>libc.Int32FromInt32(18)&libc.Uint32FromInt32(0x03))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c>>libc.Int32FromInt32(10)&libc.Uint32FromInt32(0x003F) + (c-libc.Uint32FromInt32(0x10000))>>libc.Int32FromInt32(10)&libc.Uint32FromInt32(0x00C0))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(libc.Uint32FromInt32(0x00DC) + c>>libc.Int32FromInt32(8)&libc.Uint32FromInt32(0x03))
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0x00FF))
				}
			}
		}
		(*TMem)(unsafe.Pointer(pMem)).Fn = int32(z) - int32(zOut)
		v1 = z
		z = z + 1
		**(**uint8)(__ccgo_up(v1)) = uint8(0)
	} else {
		if libc.Int32FromUint8((*TMem)(unsafe.Pointer(pMem)).Fenc) == int32(SQLITE_UTF16LE) {
			/* UTF-16 Little-endian -> UTF-8 */
			for zIn < zTerm {
				v1 = zIn
				zIn = zIn + 1
				c = uint32(**(**uint8)(__ccgo_up(v1)))
				v1 = zIn
				zIn = zIn + 1
				c = c + libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1)))<<int32(8))
				if c >= uint32(0xd800) && c < uint32(0xe000) {
					if zIn < zTerm {
						v1 = zIn
						zIn = zIn + 1
						c2 = libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1)))
						v2 = zIn
						zIn = zIn + 1
						c2 = c2 + libc.Int32FromUint8(**(**uint8)(__ccgo_up(v2)))<<int32(8)
						c = libc.Uint32FromInt32(c2&libc.Int32FromInt32(0x03FF)) + c&uint32(0x003F)<<int32(10) + (c&uint32(0x03C0)+uint32(0x0040))<<int32(10)
					}
				}
				if c < uint32(0x00080) {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0xFF))
				} else {
					if c < uint32(0x00800) {
						v1 = z
						z = z + 1
						**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xC0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x1F))))
						v1 = z
						z = z + 1
						**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
					} else {
						if c < uint32(0x10000) {
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xE0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x0F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
						} else {
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xF0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(18)&libc.Uint32FromInt32(0x07))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
						}
					}
				}
			}
		} else {
			/* UTF-16 Big-endian -> UTF-8 */
			for zIn < zTerm {
				v1 = zIn
				zIn = zIn + 1
				c = libc.Uint32FromInt32(libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))) << int32(8))
				v1 = zIn
				zIn = zIn + 1
				c = c + uint32(**(**uint8)(__ccgo_up(v1)))
				if c >= uint32(0xd800) && c < uint32(0xe000) {
					if zIn < zTerm {
						v1 = zIn
						zIn = zIn + 1
						c21 = libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))) << int32(8)
						v2 = zIn
						zIn = zIn + 1
						c21 = c21 + libc.Int32FromUint8(**(**uint8)(__ccgo_up(v2)))
						c = libc.Uint32FromInt32(c21&libc.Int32FromInt32(0x03FF)) + c&uint32(0x003F)<<int32(10) + (c&uint32(0x03C0)+uint32(0x0040))<<int32(10)
					}
				}
				if c < uint32(0x00080) {
					v1 = z
					z = z + 1
					**(**uint8)(__ccgo_up(v1)) = uint8(c & libc.Uint32FromInt32(0xFF))
				} else {
					if c < uint32(0x00800) {
						v1 = z
						z = z + 1
						**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xC0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x1F))))
						v1 = z
						z = z + 1
						**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
					} else {
						if c < uint32(0x10000) {
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xE0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x0F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
						} else {
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0xF0) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(18)&libc.Uint32FromInt32(0x07))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(12)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c>>libc.Int32FromInt32(6)&libc.Uint32FromInt32(0x3F))))
							v1 = z
							z = z + 1
							**(**uint8)(__ccgo_up(v1)) = libc.Uint8FromInt32(int32(0x80) + libc.Int32FromUint8(uint8(c&libc.Uint32FromInt32(0x3F))))
						}
					}
				}
			}
		}
		(*TMem)(unsafe.Pointer(pMem)).Fn = int32(z) - int32(zOut)
	}
	**(**uint8)(__ccgo_up(z)) = uint8(0)
	c = libc.Uint32FromInt32(libc.Int32FromInt32(MEM_Str) | libc.Int32FromInt32(MEM_Term) | libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem)).Fflags)&(libc.Int32FromInt32(MEM_AffMask)|libc.Int32FromInt32(MEM_Subtype)))
	_sqlite3VdbeMemRelease(tls, pMem)
	(*TMem)(unsafe.Pointer(pMem)).Fflags = uint16(c)
	(*TMem)(unsafe.Pointer(pMem)).Fenc = desiredEnc
	(*TMem)(unsafe.Pointer(pMem)).Fz = zOut
	(*TMem)(unsafe.Pointer(pMem)).FzMalloc = (*TMem)(unsafe.Pointer(pMem)).Fz
	(*TMem)(unsafe.Pointer(pMem)).FszMalloc = _sqlite3DbMallocSize(tls, (*TMem)(unsafe.Pointer(pMem)).Fdb, (*TMem)(unsafe.Pointer(pMem)).Fz)
	goto translate_out
translate_out:
	;
	return SQLITE_OK
	return r
}

// C documentation
//
//	/*
//	** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
//	** QUERY PLAN output.
//	**
//	** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no
//	** more opcodes to be displayed.
//	*/
func _sqlite3VdbeNextOpcode(tls *libc.TLS, p uintptr, pSub uintptr, eMode int32, piPc uintptr, piAddr uintptr, paOp uintptr) (r int32) {
	var aOp, apSub uintptr
	var i, iPc, j, j1, nByte, nRow, nSub, rc, v2 int32
	_, _, _, _, _, _, _, _, _, _, _ = aOp, apSub, i, iPc, j, j1, nByte, nRow, nSub, rc, v2 /* Stop when row count reaches this */
	nSub = 0                                                                               /* Number of sub-vdbes seen so far */
	apSub = uintptr(0)                                                                     /* Next instruction address */
	rc = SQLITE_OK                                                                         /* Result code */
	aOp = uintptr(0)                                                                       /* Rowid.  Copy of value in *piPc */
	/* When the number of output rows reaches nRow, that means the
	 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
	 ** nRow is the sum of the number of rows in the main program, plus
	 ** the sum of the number of rows in all trigger subprograms encountered
	 ** so far.  The nRow value will increase as new trigger subprograms are
	 ** encountered, but p->pc will eventually catch up to nRow.
	 */
	nRow = (*TVdbe)(unsafe.Pointer(p)).FnOp
	if pSub != uintptr(0) {
		if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pSub)).Fflags)&int32(MEM_Blob) != 0 {
			/* pSub is initiallly NULL.  It is initialized to a BLOB by
			 ** the P4_SUBPROGRAM processing logic below */
			nSub = libc.Int32FromUint32(libc.Uint32FromInt32((*TMem)(unsafe.Pointer(pSub)).Fn) / uint32(4))
			apSub = (*TMem)(unsafe.Pointer(pSub)).Fz
		}
		i = 0
		for {
			if !(i < nSub) {
				break
			}
			nRow = nRow + (*TSubProgram)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apSub + uintptr(i)*4)))).FnOp
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	iPc = **(**int32)(__ccgo_up(piPc))
	for int32(1) != 0 { /* Loop exits via break */
		v2 = iPc
		iPc = iPc + 1
		i = v2
		if i >= nRow {
			(*TVdbe)(unsafe.Pointer(p)).Frc = SQLITE_OK
			rc = int32(SQLITE_DONE)
			break
		}
		if i < (*TVdbe)(unsafe.Pointer(p)).FnOp {
			/* The rowid is small enough that we are still in the
			 ** main program. */
			aOp = (*TVdbe)(unsafe.Pointer(p)).FaOp
		} else {
			i = i - (*TVdbe)(unsafe.Pointer(p)).FnOp
			j = 0
			for {
				if !(i >= (*TSubProgram)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apSub + uintptr(j)*4)))).FnOp) {
					break
				}
				i = i - (*TSubProgram)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apSub + uintptr(j)*4)))).FnOp
				goto _3
			_3:
				;
				j = j + 1
			}
			aOp = (*TSubProgram)(unsafe.Pointer(**(**uintptr)(__ccgo_up(apSub + uintptr(j)*4)))).FaOp
		}
		/* When an OP_Program opcode is encounter (the only opcode that has
		 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
		 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
		 ** has not already been seen.
		 */
		if pSub != uintptr(0) && int32((**(**TOp)(__ccgo_up(aOp + uintptr(i)*20))).Fp4type) == -int32(4) {
			nByte = libc.Int32FromUint32(libc.Uint32FromInt32(nSub+libc.Int32FromInt32(1)) * uint32(4))
			j1 = 0
			for {
				if !(j1 < nSub) {
					break
				}
				if **(**uintptr)(__ccgo_up(apSub + uintptr(j1)*4)) == *(*uintptr)(unsafe.Pointer(aOp + uintptr(i)*20 + 16)) {
					break
				}
				goto _4
			_4:
				;
				j1 = j1 + 1
			}
			if j1 == nSub {
				(*TVdbe)(unsafe.Pointer(p)).Frc = _sqlite3VdbeMemGrow(tls, pSub, nByte, libc.BoolInt32(nSub != 0))
				if (*TVdbe)(unsafe.Pointer(p)).Frc != SQLITE_OK {
					rc = int32(SQLITE_ERROR)
					break
				}
				apSub = (*TMem)(unsafe.Pointer(pSub)).Fz
				v2 = nSub
				nSub = nSub + 1
				**(**uintptr)(__ccgo_up(apSub + uintptr(v2)*4)) = *(*uintptr)(unsafe.Pointer(aOp + uintptr(i)*20 + 16))
				(*TMem)(unsafe.Pointer(pSub)).Fflags = libc.Uint16FromInt32(libc.Int32FromUint16((*TMem)(unsafe.Pointer(pSub)).Fflags) & ^(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Zero)) | int32(MEM_Blob))
				(*TMem)(unsafe.Pointer(pSub)).Fn = libc.Int32FromUint32(libc.Uint32FromInt32(nSub) * uint32(4))
				nRow = nRow + (*TSubProgram)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(aOp + uintptr(i)*20 + 16)))).FnOp
			}
		}
		if eMode == 0 {
			break
		}
		if libc.Int32FromUint8((**(**TOp)(__ccgo_up(aOp + uintptr(i)*20))).Fopcode) == int32(OP_Explain) {
			break
		}
		if libc.Int32FromUint8((**(**TOp)(__ccgo_up(aOp + uintptr(i)*20))).Fopcode) == int32(OP_Init) && iPc > int32(1) {
			break
		}
	}
	**(**int32)(__ccgo_up(piPc)) = iPc
	**(**int32)(__ccgo_up(piAddr)) = i
	**(**uintptr)(__ccgo_up(paOp)) = aOp
	return rc
}

// C documentation
//
//	/*
//	** Given the nKey-byte encoding of a record in pKey[], populate the
//	** UnpackedRecord structure indicated by the fourth argument with the
//	** contents of the decoded record.
//	*/
func _sqlite3VdbeRecordUnpack(tls *libc.TLS, nKey int32, pKey uintptr, p uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aKey, pKeyInfo, pMem uintptr
	var d, idx Tu32
	var u, v3 Tu16
	var v1 int32
	var _ /* serial_type at bp+4 */ Tu32
	var _ /* szHdr at bp+0 */ Tu32
	_, _, _, _, _, _, _, _ = aKey, d, idx, pKeyInfo, pMem, u, v1, v3
	aKey = pKey
	pMem = (*TUnpackedRecord)(unsafe.Pointer(p)).FaMem
	pKeyInfo = (*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo
	(*TUnpackedRecord)(unsafe.Pointer(p)).Fdefault_rc = 0
	if libc.Int32FromUint8(**(**uint8)(__ccgo_up(aKey))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
		**(**Tu32)(__ccgo_up(bp)) = uint32(**(**uint8)(__ccgo_up(aKey)))
		v1 = libc.Int32FromInt32(1)
	} else {
		v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aKey, bp))
	}
	idx = uint32(libc.Uint8FromInt32(v1))
	d = **(**Tu32)(__ccgo_up(bp))
	u = uint16(0)
	for idx < **(**Tu32)(__ccgo_up(bp)) && d <= libc.Uint32FromInt32(nKey) {
		if libc.Int32FromUint8(**(**uint8)(__ccgo_up(aKey + uintptr(idx)))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
			**(**Tu32)(__ccgo_up(bp + 4)) = uint32(**(**uint8)(__ccgo_up(aKey + uintptr(idx))))
			v1 = libc.Int32FromInt32(1)
		} else {
			v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aKey+uintptr(idx), bp+4))
		}
		idx = idx + uint32(libc.Uint8FromInt32(v1))
		(*TMem)(unsafe.Pointer(pMem)).Fenc = (*TKeyInfo)(unsafe.Pointer(pKeyInfo)).Fenc
		(*TMem)(unsafe.Pointer(pMem)).Fdb = (*TKeyInfo)(unsafe.Pointer(pKeyInfo)).Fdb
		/* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
		(*TMem)(unsafe.Pointer(pMem)).FszMalloc = 0
		(*TMem)(unsafe.Pointer(pMem)).Fz = uintptr(0)
		_sqlite3VdbeSerialGet(tls, aKey+uintptr(d), **(**Tu32)(__ccgo_up(bp + 4)), pMem)
		d = d + _sqlite3VdbeSerialTypeLen(tls, **(**Tu32)(__ccgo_up(bp + 4)))
		u = u + 1
		v3 = u
		if libc.Int32FromUint16(v3) >= libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(p)).FnField) {
			break
		}
		pMem += 40
	}
	if d > libc.Uint32FromInt32(nKey) && u != 0 {
		/* In a corrupt record entry, the last pMem might have been set up using
		 ** uninitialized memory. Overwrite its value with NULL, to prevent
		 ** warnings from MSAN. */
		_sqlite3VdbeMemSetNull(tls, pMem-libc.BoolUintptr(libc.Int32FromUint16(u) < libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(p)).FnField))*40)
	}
	(*TUnpackedRecord)(unsafe.Pointer(p)).FnField = u
}

// C documentation
//
//	/*
//	** Mark the VDBE as one that can be run multiple times.
//	*/
func _sqlite3VdbeReusable(tls *libc.TLS, p uintptr) {
	var i int32
	_ = i
	i = int32(1)
	for {
		if !(i < (*TVdbe)(unsafe.Pointer(p)).FnOp) {
			break
		}
		if libc.Int32FromUint8((**(**TOp)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FaOp + uintptr(i)*20))).Fopcode) == int32(OP_Expire) {
			(**(**TOp)(__ccgo_up((*TVdbe)(unsafe.Pointer(p)).FaOp + 1*20))).Fopcode = uint8(OP_Noop)
			break
		}
		goto _1
	_1:
		;
		i = i + 1
	}
}

// C documentation
//
//	/*
//	** Set the name of the idx'th column to be returned by the SQL statement.
//	** zName must be a pointer to a nul terminated string.
//	**
//	** This call must be made after a call to sqlite3VdbeSetNumCols().
//	**
//	** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
//	** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
//	** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
//	*/
func _sqlite3VdbeSetColName(tls *libc.TLS, p uintptr, idx int32, var1 int32, zName uintptr, __ccgo_fp_xDel uintptr) (r int32) {
	var pColName uintptr
	var rc int32
	_, _ = pColName, rc
	if (*Tsqlite3)(unsafe.Pointer((*TVdbe)(unsafe.Pointer(p)).Fdb)).FmallocFailed != 0 {
		return int32(SQLITE_NOMEM)
	}
	pColName = (*TVdbe)(unsafe.Pointer(p)).FaColName + uintptr(idx+var1*libc.Int32FromUint16((*TVdbe)(unsafe.Pointer(p)).FnResAlloc))*40
	rc = _sqlite3VdbeMemSetText(tls, pColName, zName, int64(-int32(1)), __ccgo_fp_xDel)
	return rc
}

// C documentation
//
//	/*
//	** Set the number of result columns that will be returned by this SQL
//	** statement. This is now set at compile time, rather than during
//	** execution of the vdbe program so that sqlite3_column_count() can
//	** be called on an SQL statement before sqlite3_step().
//	*/
func _sqlite3VdbeSetNumCols(tls *libc.TLS, p uintptr, nResColumn int32) {
	var db uintptr
	var n int32
	var v1 Tu16
	_, _, _ = db, n, v1
	db = (*TVdbe)(unsafe.Pointer(p)).Fdb
	if (*TVdbe)(unsafe.Pointer(p)).FnResAlloc != 0 {
		_releaseMemArray(tls, (*TVdbe)(unsafe.Pointer(p)).FaColName, libc.Int32FromUint16((*TVdbe)(unsafe.Pointer(p)).FnResAlloc)*int32(COLNAME_N))
		_sqlite3DbFree(tls, db, (*TVdbe)(unsafe.Pointer(p)).FaColName)
	}
	n = nResColumn * int32(COLNAME_N)
	v1 = libc.Uint16FromInt32(nResColumn)
	(*TVdbe)(unsafe.Pointer(p)).FnResAlloc = v1
	(*TVdbe)(unsafe.Pointer(p)).FnResColumn = v1
	(*TVdbe)(unsafe.Pointer(p)).FaColName = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(40)*libc.Uint32FromInt32(n)))
	if (*TVdbe)(unsafe.Pointer(p)).FaColName == uintptr(0) {
		return
	}
	_initMemArray(tls, (*TVdbe)(unsafe.Pointer(p)).FaColName, n, db, uint16(MEM_Null))
}

// C documentation
//
//	/*
//	** Compare the key in memory cell pVal with the key that the sorter cursor
//	** passed as the first argument currently points to. For the purposes of
//	** the comparison, ignore the rowid field at the end of each record.
//	**
//	** If the sorter cursor key contains any NULL values, consider it to be
//	** less than pVal. Even if pVal also contains NULL values.
//	**
//	** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
//	** Otherwise, set *pRes to a negative, zero or positive value if the
//	** key in pVal is smaller than, equal to or larger than the current sorter
//	** key.
//	**
//	** This routine forms the core of the OP_SorterCompare opcode, which in
//	** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
//	*/
func _sqlite3VdbeSorterCompare(tls *libc.TLS, pCsr uintptr, pVal uintptr, nKeyCol int32, pRes uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i int32
	var pKey, pKeyInfo, pSorter, r2, v1 uintptr
	var _ /* nKey at bp+0 */ int32
	_, _, _, _, _, _ = i, pKey, pKeyInfo, pSorter, r2, v1 /* Sorter key to compare pVal with */
	pSorter = *(*uintptr)(unsafe.Pointer(pCsr + 36))
	r2 = (*TVdbeSorter)(unsafe.Pointer(pSorter)).FpUnpacked
	pKeyInfo = (*TVdbeCursor)(unsafe.Pointer(pCsr)).FpKeyInfo
	if r2 == uintptr(0) {
		v1 = _sqlite3VdbeAllocUnpackedRecord(tls, pKeyInfo)
		(*TVdbeSorter)(unsafe.Pointer(pSorter)).FpUnpacked = v1
		r2 = v1
		if r2 == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		(*TUnpackedRecord)(unsafe.Pointer(r2)).FnField = libc.Uint16FromInt32(nKeyCol)
	}
	pKey = _vdbeSorterRowkey(tls, pSorter, bp)
	_sqlite3VdbeRecordUnpack(tls, **(**int32)(__ccgo_up(bp)), pKey, r2)
	i = 0
	for {
		if !(i < nKeyCol) {
			break
		}
		if libc.Int32FromUint16((**(**TMem)(__ccgo_up((*TUnpackedRecord)(unsafe.Pointer(r2)).FaMem + uintptr(i)*40))).Fflags)&int32(MEM_Null) != 0 {
			**(**int32)(__ccgo_up(pRes)) = -int32(1)
			return SQLITE_OK
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	**(**int32)(__ccgo_up(pRes)) = _sqlite3VdbeRecordCompare(tls, (*TMem)(unsafe.Pointer(pVal)).Fn, (*TMem)(unsafe.Pointer(pVal)).Fz, r2)
	return SQLITE_OK
}

/************** End of vdbesort.c ********************************************/
/************** Begin file vdbevtab.c ****************************************/
/*
** 2020-03-23
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements virtual-tables for examining the bytecode content
** of a prepared statement.
 */
/* #include "sqliteInt.h" */

/************** End of vdbevtab.c ********************************************/
/************** Begin file memjournal.c **************************************/
/*
** 2008 October 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to implement an in-memory rollback journal.
** The in-memory rollback journal is used to journal transactions for
** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
**
** Update:  The in-memory journal is also used to temporarily cache
** smaller journals that are not critical for power-loss recovery.
** For example, statement journals that are not too big will be held
** entirely in memory, thus reducing the number of file I/O calls, and
** more importantly, reducing temporary file creation events.  If these
** journals become too large for memory, they are spilled to disk.  But
** in the common case, they are usually small and no file I/O needs to
** occur.
 */
/* #include "sqliteInt.h" */

// C documentation
//
//	/*
//	** Copy the current sorter key into the memory cell pOut.
//	*/
func _sqlite3VdbeSorterRowkey(tls *libc.TLS, pCsr uintptr, pOut uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pKey, pSorter uintptr
	var _ /* nKey at bp+0 */ int32
	_, _ = pKey, pSorter /* Sorter key to copy into pOut */
	pSorter = *(*uintptr)(unsafe.Pointer(pCsr + 36))
	pKey = _vdbeSorterRowkey(tls, pSorter, bp)
	if _sqlite3VdbeMemClearAndResize(tls, pOut, **(**int32)(__ccgo_up(bp))) != 0 {
		return int32(SQLITE_NOMEM)
	}
	(*TMem)(unsafe.Pointer(pOut)).Fn = **(**int32)(__ccgo_up(bp))
	(*TMem)(unsafe.Pointer(pOut)).Fflags = libc.Uint16FromInt32(libc.Int32FromUint16((*TMem)(unsafe.Pointer(pOut)).Fflags) & ^(libc.Int32FromInt32(MEM_TypeMask)|libc.Int32FromInt32(MEM_Zero)) | int32(MEM_Blob))
	libc.Xmemcpy(tls, (*TMem)(unsafe.Pointer(pOut)).Fz, pKey, libc.Uint32FromInt32(**(**int32)(__ccgo_up(bp))))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Return a pointer to a subexpression of pVector that is the i-th
//	** column of the vector (numbered starting with 0).  The caller must
//	** ensure that i is within range.
//	**
//	** If pVector is really a scalar (and "scalar" here includes subqueries
//	** that return a single column!) then return pVector unmodified.
//	**
//	** pVector retains ownership of the returned subexpression.
//	**
//	** If the vector is a (SELECT ...) then the expression returned is
//	** just the expression for the i-th term of the result set, and may
//	** not be ready for evaluation because the table cursor has not yet
//	** been positioned.
//	*/
func _sqlite3VectorFieldSubexpr(tls *libc.TLS, pVector uintptr, i int32) (r uintptr) {
	if _sqlite3ExprIsVector(tls, pVector) != 0 {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pVector)).Fop) == int32(TK_SELECT) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pVector)).Fop2) == int32(TK_SELECT) {
			return (*(*TExprList_item)(unsafe.Pointer((*TSelect)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pVector + 20)))).FpEList + 8 + uintptr(i)*20))).FpExpr
		} else {
			return (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pVector + 20)) + 8 + uintptr(i)*20))).FpExpr
		}
	}
	return pVector
}

// C documentation
//
//	/*
//	** The parser calls this routine for each token after the first token
//	** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
//	*/
func _sqlite3VtabArgExtend(tls *libc.TLS, pParse uintptr, p uintptr) {
	var pArg uintptr
	_ = pArg
	pArg = pParse + 264
	if (*TToken)(unsafe.Pointer(pArg)).Fz == uintptr(0) {
		(*TToken)(unsafe.Pointer(pArg)).Fz = (*TToken)(unsafe.Pointer(p)).Fz
		(*TToken)(unsafe.Pointer(pArg)).Fn = (*TToken)(unsafe.Pointer(p)).Fn
	} else {
		(*TToken)(unsafe.Pointer(pArg)).Fn = libc.Uint32FromInt32(t__predefined_ptrdiff_t((*TToken)(unsafe.Pointer(p)).Fz+uintptr((*TToken)(unsafe.Pointer(p)).Fn)) - int32((*TToken)(unsafe.Pointer(pArg)).Fz))
	}
}

// C documentation
//
//	/*
//	** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
//	** statement.  The module name has been parsed, but the optional list
//	** of parameters that follow the module name are still pending.
//	*/
func _sqlite3VtabBeginParse(tls *libc.TLS, pParse uintptr, pName1 uintptr, pName2 uintptr, pModuleName uintptr, ifNotExists int32) {
	var db, pTable uintptr
	var iDb int32
	_, _, _ = db, iDb, pTable /* Database connection */
	_sqlite3StartTable(tls, pParse, pName1, pName2, 0, 0, int32(1), ifNotExists)
	pTable = (*TParse)(unsafe.Pointer(pParse)).FpNewTable
	if pTable == uintptr(0) {
		return
	}
	(*TTable)(unsafe.Pointer(pTable)).FeTabType = uint8(TABTYP_VTAB)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	_addModuleArgument(tls, pParse, pTable, _sqlite3NameFromToken(tls, db, pModuleName))
	_addModuleArgument(tls, pParse, pTable, uintptr(0))
	_addModuleArgument(tls, pParse, pTable, _sqlite3DbStrDup(tls, db, (*TTable)(unsafe.Pointer(pTable)).FzName))
	(*TParse)(unsafe.Pointer(pParse)).FsNameToken.Fn = libc.Uint32FromInt32(t__predefined_ptrdiff_t((*TToken)(unsafe.Pointer(pModuleName)).Fz+uintptr((*TToken)(unsafe.Pointer(pModuleName)).Fn)) - int32((*TParse)(unsafe.Pointer(pParse)).FsNameToken.Fz))
	/* Creating a virtual table invokes the authorization callback twice.
	 ** The first invocation, to obtain permission to INSERT a row into the
	 ** sqlite_schema table, has already been made by sqlite3StartTable().
	 ** The second call, to obtain permission to create the table, is made now.
	 */
	if (*(*struct {
		FnArg  int32
		FazArg uintptr
		Fp     uintptr
	})(unsafe.Pointer(pTable + 44))).FazArg != 0 {
		iDb = _sqlite3SchemaToIndex(tls, db, (*TTable)(unsafe.Pointer(pTable)).FpSchema)
		/* The database the table is being created in */
		_sqlite3AuthCheck(tls, pParse, int32(SQLITE_CREATE_VTABLE), (*TTable)(unsafe.Pointer(pTable)).FzName, **(**uintptr)(__ccgo_up((*(*struct {
			FnArg  int32
			FazArg uintptr
			Fp     uintptr
		})(unsafe.Pointer(pTable + 44))).FazArg)), (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FaDb + uintptr(iDb)*16))).FzDbSName)
	}
}

// C documentation
//
//	/*
//	** This function is invoked by the vdbe to call the xDestroy method
//	** of the virtual table named zTab in database iDb. This occurs
//	** when a DROP TABLE is mentioned.
//	**
//	** This call is a no-op if zTab is not a virtual table.
//	*/
func _sqlite3VtabCallDestroy(tls *libc.TLS, db uintptr, iDb int32, zTab uintptr) (r int32) {
	var p, pTab, xDestroy uintptr
	var rc int32
	_, _, _, _ = p, pTab, rc, xDestroy
	rc = SQLITE_OK
	pTab = _sqlite3FindTable(tls, db, zTab, (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName)
	if pTab != uintptr(0) && libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VTAB) && (*(*struct {
		FnArg  int32
		FazArg uintptr
		Fp     uintptr
	})(unsafe.Pointer(pTab + 44))).Fp != uintptr(0) {
		p = (*(*struct {
			FnArg  int32
			FazArg uintptr
			Fp     uintptr
		})(unsafe.Pointer(pTab + 44))).Fp
		for {
			if !(p != 0) {
				break
			}
			if (*Tsqlite3_vtab)(unsafe.Pointer((*TVTable)(unsafe.Pointer(p)).FpVtab)).FnRef > 0 {
				return int32(SQLITE_LOCKED)
			}
			goto _1
		_1:
			;
			p = (*TVTable)(unsafe.Pointer(p)).FpNext
		}
		p = _vtabDisconnectAll(tls, db, pTab)
		xDestroy = (*Tsqlite3_module)(unsafe.Pointer((*TModule)(unsafe.Pointer((*TVTable)(unsafe.Pointer(p)).FpMod)).FpModule)).FxDestroy
		if xDestroy == uintptr(0) {
			xDestroy = (*Tsqlite3_module)(unsafe.Pointer((*TModule)(unsafe.Pointer((*TVTable)(unsafe.Pointer(p)).FpMod)).FpModule)).FxDisconnect
		}
		(*TTable)(unsafe.Pointer(pTab)).FnTabRef = (*TTable)(unsafe.Pointer(pTab)).FnTabRef + 1
		rc = (*(*func(*libc.TLS, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{xDestroy})))(tls, (*TVTable)(unsafe.Pointer(p)).FpVtab)
		/* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
		if rc == SQLITE_OK {
			(*TVTable)(unsafe.Pointer(p)).FpVtab = uintptr(0)
			(*(*struct {
				FnArg  int32
				FazArg uintptr
				Fp     uintptr
			})(unsafe.Pointer(pTab + 44))).Fp = uintptr(0)
			_sqlite3VtabUnlock(tls, p)
		}
		_sqlite3DeleteTable(tls, db, pTab)
	}
	return rc
}

// C documentation
//
//	/*
//	** Invoke the xCommit method of all virtual tables in the
//	** sqlite3.aVTrans array. Then clear the array itself.
//	*/
func _sqlite3VtabCommit(tls *libc.TLS, db uintptr) (r int32) {
	_callFinaliser(tls, db, libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0)+64)))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
//	** array so that an OP_VBegin will get generated for it.  Add pTab to the
//	** array if it is missing.  If pTab is already in the array, this routine
//	** is a no-op.
//	*/
func _sqlite3VtabMakeWritable(tls *libc.TLS, pParse uintptr, pTab uintptr) {
	var apVtabLock, pToplevel, v1 uintptr
	var i, n, v3 int32
	_, _, _, _, _, _ = apVtabLock, i, n, pToplevel, v1, v3
	if (*TParse)(unsafe.Pointer(pParse)).FpToplevel != 0 {
		v1 = (*TParse)(unsafe.Pointer(pParse)).FpToplevel
	} else {
		v1 = pParse
	}
	pToplevel = v1
	i = 0
	for {
		if !(i < (*TParse)(unsafe.Pointer(pToplevel)).FnVtabLock) {
			break
		}
		if pTab == **(**uintptr)(__ccgo_up((*TParse)(unsafe.Pointer(pToplevel)).FapVtabLock + uintptr(i)*4)) {
			return
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	n = libc.Int32FromUint32(libc.Uint32FromInt32((*TParse)(unsafe.Pointer(pToplevel)).FnVtabLock+libc.Int32FromInt32(1)) * uint32(4))
	apVtabLock = _sqlite3Realloc(tls, (*TParse)(unsafe.Pointer(pToplevel)).FapVtabLock, libc.Uint64FromInt32(n))
	if apVtabLock != 0 {
		(*TParse)(unsafe.Pointer(pToplevel)).FapVtabLock = apVtabLock
		v1 = pToplevel + 224
		v3 = *(*int32)(unsafe.Pointer(v1))
		*(*int32)(unsafe.Pointer(v1)) = *(*int32)(unsafe.Pointer(v1)) + 1
		**(**uintptr)(__ccgo_up((*TParse)(unsafe.Pointer(pToplevel)).FapVtabLock + uintptr(v3)*4)) = pTab
	} else {
		_sqlite3OomFault(tls, (*TParse)(unsafe.Pointer(pToplevel)).Fdb)
	}
}

// C documentation
//
//	/*
//	** The first parameter (pDef) is a function implementation.  The
//	** second parameter (pExpr) is the first argument to this function.
//	** If pExpr is a column in a virtual table, then let the virtual
//	** table implementation have an opportunity to overload the function.
//	**
//	** This routine is used to allow virtual table implementations to
//	** overload MATCH, LIKE, GLOB, and REGEXP operators.
//	**
//	** Return either the pDef argument (indicating no change) or a
//	** new FuncDef structure that is marked as ephemeral using the
//	** SQLITE_FUNC_EPHEM flag.
//	*/
func _sqlite3VtabOverloadFunction(tls *libc.TLS, db uintptr, pDef uintptr, nArg int32, pExpr uintptr) (r uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var pMod, pNew, pTab, pVtab uintptr
	var rc int32
	var _ /* pArg at bp+4 */ uintptr
	var _ /* xSFunc at bp+0 */ uintptr
	_, _, _, _, _ = pMod, pNew, pTab, pVtab, rc
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0)
	rc = 0
	/* Check to see the left operand is a column in a virtual table */
	if pExpr == uintptr(0) {
		return pDef
	}
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_COLUMN) {
		return pDef
	}
	pTab = (*TExpr)(unsafe.Pointer(pExpr)).Fy.FpTab
	if pTab == uintptr(0) {
		return pDef
	}
	if !(libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == libc.Int32FromInt32(TABTYP_VTAB)) {
		return pDef
	}
	pVtab = (*TVTable)(unsafe.Pointer(_sqlite3GetVTable(tls, db, pTab))).FpVtab
	pMod = (*Tsqlite3_vtab)(unsafe.Pointer(pVtab)).FpModule
	if (*Tsqlite3_module)(unsafe.Pointer(pMod)).FxFindFunction == uintptr(0) {
		return pDef
	}
	/* Call the xFindFunction method on the virtual table implementation
	 ** to see if the implementation wants to overload this function.
	 **
	 ** Though undocumented, we have historically always invoked xFindFunction
	 ** with an all lower-case function name.  Continue in this tradition to
	 ** avoid any chance of an incompatibility.
	 */
	rc = (*(*func(*libc.TLS, uintptr, int32, uintptr, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*Tsqlite3_module)(unsafe.Pointer(pMod)).FxFindFunction})))(tls, pVtab, nArg, (*TFuncDef)(unsafe.Pointer(pDef)).FzName, bp, bp+4)
	if rc == 0 {
		return pDef
	}
	/* Create a new ephemeral function definition for the overloaded
	 ** function */
	pNew = _sqlite3DbMallocZero(tls, db, uint64(uint32(40)+libc.Uint32FromInt32(_sqlite3Strlen30(tls, (*TFuncDef)(unsafe.Pointer(pDef)).FzName))+uint32(1)))
	if pNew == uintptr(0) {
		return pDef
	}
	**(**TFuncDef)(__ccgo_up(pNew)) = **(**TFuncDef)(__ccgo_up(pDef))
	(*TFuncDef)(unsafe.Pointer(pNew)).FzName = pNew + 1*40
	libc.Xmemcpy(tls, pNew+1*40, (*TFuncDef)(unsafe.Pointer(pDef)).FzName, libc.Uint32FromInt32(_sqlite3Strlen30(tls, (*TFuncDef)(unsafe.Pointer(pDef)).FzName)+int32(1)))
	(*TFuncDef)(unsafe.Pointer(pNew)).FxSFunc = **(**uintptr)(__ccgo_up(bp))
	(*TFuncDef)(unsafe.Pointer(pNew)).FpUserData = **(**uintptr)(__ccgo_up(bp + 4))
	**(**Tu32)(__ccgo_up(pNew + 4)) |= uint32(SQLITE_FUNC_EPHEM)
	return pNew
}

// C documentation
//
//	/*
//	** Invoke the xRollback method of all virtual tables in the
//	** sqlite3.aVTrans array. Then clear the array itself.
//	*/
func _sqlite3VtabRollback(tls *libc.TLS, db uintptr) (r int32) {
	_callFinaliser(tls, db, libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0)+68)))
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** This routine is called to implement sqlite3_wal_checkpoint() and
//	** related interfaces.
//	**
//	** Obtain a CHECKPOINT lock and then backfill as much information as
//	** we can from WAL into the database.
//	**
//	** If parameter xBusy is not NULL, it is a pointer to a busy-handler
//	** callback. In this case this function runs a blocking checkpoint.
//	*/
func _sqlite3WalCheckpoint(tls *libc.TLS, pWal uintptr, db uintptr, eMode int32, __ccgo_fp_xBusy uintptr, pBusyArg uintptr, sync_flags int32, nBuf int32, zBuf uintptr, pnLog uintptr, pnCkpt uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var eMode2, rc, v1 int32
	var xBusy2 uintptr
	var _ /* isChanged at bp+0 */ int32
	_, _, _, _ = eMode2, rc, xBusy2, v1 /* Return code */
	**(**int32)(__ccgo_up(bp)) = 0      /* True if a new wal-index header is loaded */
	eMode2 = eMode                      /* Mode to pass to walCheckpoint() */
	xBusy2 = __ccgo_fp_xBusy            /* Busy handler for eMode2 */
	/* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
	 ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
	if (*TWal)(unsafe.Pointer(pWal)).FreadOnly != 0 {
		return int32(SQLITE_READONLY)
	}
	/* Enable blocking locks, if possible. */
	if xBusy2 != 0 {
	}
	/* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
	 ** "checkpoint" lock on the database file.
	 ** EVIDENCE-OF: R-10421-19736 If any other process is running a
	 ** checkpoint operation at the same time, the lock cannot be obtained and
	 ** SQLITE_BUSY is returned.
	 ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
	 ** it will not be invoked in this case.
	 */
	if eMode != -int32(1) {
		rc = _walLockExclusive(tls, pWal, int32(WAL_CKPT_LOCK), int32(1))
		if rc == SQLITE_OK {
			(*TWal)(unsafe.Pointer(pWal)).FckptLock = uint8(1)
			/* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART
			 ** and TRUNCATE modes also obtain the exclusive "writer" lock on the
			 ** database file.
			 **
			 ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
			 ** immediately, and a busy-handler is configured, it is invoked and the
			 ** writer lock retried until either the busy-handler returns 0 or the
			 ** lock is successfully obtained.
			 */
			if eMode != SQLITE_CHECKPOINT_PASSIVE {
				rc = _walBusyLock(tls, pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, int32(1))
				if rc == SQLITE_OK {
					(*TWal)(unsafe.Pointer(pWal)).FwriteLock = uint8(1)
				} else {
					if rc == int32(SQLITE_BUSY) {
						eMode2 = SQLITE_CHECKPOINT_PASSIVE
						xBusy2 = uintptr(0)
						rc = SQLITE_OK
					}
				}
			}
		}
	} else {
		rc = SQLITE_OK
	}
	/* Read the wal-index header. */
	if rc == SQLITE_OK {
		/* For a passive checkpoint, do not re-enable blocking locks after
		 ** reading the wal-index header. A passive checkpoint should not block
		 ** or invoke the busy handler. The only lock such a checkpoint may
		 ** attempt to obtain is a lock on a read-slot, and it should give up
		 ** immediately and do a partial checkpoint if it cannot obtain it. */
		rc = _walIndexReadHdr(tls, pWal, bp)
		if eMode2 > SQLITE_CHECKPOINT_PASSIVE {
		}
		if **(**int32)(__ccgo_up(bp)) != 0 && (*Tsqlite3_io_methods)(unsafe.Pointer((*Tsqlite3_file)(unsafe.Pointer((*TWal)(unsafe.Pointer(pWal)).FpDbFd)).FpMethods)).FiVersion >= int32(3) {
			_sqlite3OsUnfetch(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, 0, uintptr(0))
		}
	}
	/* Copy data from the log to the database file. */
	if rc == SQLITE_OK {
		_sqlite3FaultSim(tls, int32(660))
		if (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame != 0 && _walPagesize(tls, pWal) != nBuf {
			rc = _sqlite3CorruptError(tls, int32(71912))
		} else {
			if eMode2 != -int32(1) {
				rc = _walCheckpoint(tls, pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf)
			}
		}
		/* If no error occurred, set the output variables. */
		if rc == SQLITE_OK || rc == int32(SQLITE_BUSY) {
			if pnLog != 0 {
				**(**int32)(__ccgo_up(pnLog)) = libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame)
			}
			if pnCkpt != 0 {
				**(**int32)(__ccgo_up(pnCkpt)) = libc.Int32FromUint32((*TWalCkptInfo)(unsafe.Pointer(_walCkptInfo(tls, pWal))).FnBackfill)
			}
		}
	}
	if **(**int32)(__ccgo_up(bp)) != 0 {
		/* If a new wal-index header was loaded before the checkpoint was
		 ** performed, then the pager-cache associated with pWal is now
		 ** out of date. So zero the cached wal-index header to ensure that
		 ** next time the pager opens a snapshot on this database it knows that
		 ** the cache needs to be reset.
		 */
		libc.Xmemset(tls, pWal+52, 0, uint32(48))
	}
	/* Release the locks. */
	_sqlite3WalEndWriteTransaction(tls, pWal)
	if (*TWal)(unsafe.Pointer(pWal)).FckptLock != 0 {
		_walUnlockExclusive(tls, pWal, int32(WAL_CKPT_LOCK), int32(1))
		(*TWal)(unsafe.Pointer(pWal)).FckptLock = uint8(0)
	}
	if rc == SQLITE_OK && eMode != eMode2 {
		v1 = int32(SQLITE_BUSY)
	} else {
		v1 = rc
	}
	return v1
}

// C documentation
//
//	/*
//	** Walk an expression tree.  Invoke the callback once for each node
//	** of the expression, while descending.  (In other words, the callback
//	** is invoked before visiting children.)
//	**
//	** The return value from the callback should be one of the WRC_*
//	** constants to specify how to proceed with the walk.
//	**
//	**    WRC_Continue      Continue descending down the tree.
//	**
//	**    WRC_Prune         Do not descend into child nodes, but allow
//	**                      the walk to continue with sibling nodes.
//	**
//	**    WRC_Abort         Do no more callbacks.  Unwind the stack and
//	**                      return from the top-level walk call.
//	**
//	** The return value from this routine is WRC_Abort to abandon the tree walk
//	** and WRC_Continue to continue.
//	*/
func _sqlite3WalkExprNN(tls *libc.TLS, pWalker uintptr, pExpr uintptr) (r int32) {
	var rc int32
	_ = rc
	for int32(1) != 0 {
		rc = (*(*func(*libc.TLS, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{(*TWalker)(unsafe.Pointer(pWalker)).FxExprCallback})))(tls, pWalker, pExpr)
		if rc != 0 {
			return rc & int32(WRC_Abort)
		}
		if !((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_TokenOnly)|libc.Int32FromInt32(EP_Leaf)) != libc.Uint32FromInt32(0)) {
			if (*TExpr)(unsafe.Pointer(pExpr)).FpLeft != 0 && _sqlite3WalkExprNN(tls, pWalker, (*TExpr)(unsafe.Pointer(pExpr)).FpLeft) != 0 {
				return int32(WRC_Abort)
			}
			if (*TExpr)(unsafe.Pointer(pExpr)).FpRight != 0 {
				pExpr = (*TExpr)(unsafe.Pointer(pExpr)).FpRight
				continue
			} else {
				if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
					if _sqlite3WalkSelect(tls, pWalker, *(*uintptr)(unsafe.Pointer(pExpr + 20))) != 0 {
						return int32(WRC_Abort)
					}
				} else {
					if *(*uintptr)(unsafe.Pointer(pExpr + 20)) != 0 {
						if _sqlite3WalkExprList(tls, pWalker, *(*uintptr)(unsafe.Pointer(pExpr + 20))) != 0 {
							return int32(WRC_Abort)
						}
					}
					if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
						if _walkWindowList(tls, pWalker, *(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(pExpr)).Fy)), int32(1)) != 0 {
							return int32(WRC_Abort)
						}
					}
				}
			}
		}
		break
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Possibly add terms corresponding to the LIMIT and OFFSET clauses of the
//	** SELECT statement passed as the second argument. These terms are only
//	** added if:
//	**
//	**   1. The SELECT statement has a LIMIT clause, and
//	**   2. The SELECT statement is not an aggregate or DISTINCT query, and
//	**   3. The SELECT statement has exactly one object in its FROM clause, and
//	**      that object is a virtual table, and
//	**   4. There are no terms in the WHERE clause that will not be passed
//	**      to the virtual table xBestIndex method.
//	**   5. The ORDER BY clause, if any, will be made available to the xBestIndex
//	**      method.
//	**
//	** LIMIT and OFFSET terms are ignored by most of the planner code. They
//	** exist only so that they may be passed to the xBestIndex method of the
//	** single virtual table in the FROM clause of the SELECT.
//	*/
func _sqlite3WhereAddLimit(tls *libc.TLS, pWC uintptr, p uintptr) {
	var iCsr, ii int32
	var pExpr, pOrderBy, pParent uintptr
	_, _, _, _, _ = iCsr, ii, pExpr, pOrderBy, pParent
	/* 1 -- checked by caller */
	if (*TSelect)(unsafe.Pointer(p)).FpGroupBy == uintptr(0) && (*TSelect)(unsafe.Pointer(p)).FselFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SF_Distinct)|libc.Int32FromInt32(SF_Aggregate)) == uint32(0) && ((*TSrcList)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc)).FnSrc == int32(1) && libc.Int32FromUint8((*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8))).FpSTab)).FeTabType) == int32(TABTYP_VTAB)) {
		pOrderBy = (*TSelect)(unsafe.Pointer(p)).FpOrderBy
		iCsr = (*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8))).FiCursor
		/* Check condition (4). Return early if it is not met. */
		ii = 0
		for {
			if !(ii < (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm) {
				break
			}
			if libc.Int32FromUint16((**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FwtFlags)&int32(TERM_CODED) != 0 {
				/* This term is a vector operation that has been decomposed into
				 ** other, subsequent terms.  It can be ignored. See tag-20220128a */
				goto _1
			}
			if (**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FnChild != 0 {
				/* If this term has child terms, then they are also part of the
				 ** pWC->a[] array. So this term can be ignored, as a LIMIT clause
				 ** will only be added if each of the child terms passes the
				 ** (leftCursor==iCsr) test below.  */
				goto _1
			}
			if (**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FleftCursor == iCsr && (**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FprereqRight == uint64(0) {
				goto _1
			}
			/* If this term has a parent with exactly one child, and the parent will
			 ** be passed through to xBestIndex, then this term can be ignored.  */
			if (**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FiParent >= 0 {
				pParent = (*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr((**(**TWhereTerm)(__ccgo_up((*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(ii)*48))).FiParent)*48
				if (*TWhereTerm)(unsafe.Pointer(pParent)).FleftCursor == iCsr && (*TWhereTerm)(unsafe.Pointer(pParent)).FprereqRight == uint64(0) && libc.Int32FromUint8((*TWhereTerm)(unsafe.Pointer(pParent)).FnChild) == int32(1) {
					goto _1
				}
			}
			/* This term will not be passed through. Do not add a LIMIT clause. */
			return
			goto _1
		_1:
			;
			ii = ii + 1
		}
		/* Check condition (5). Return early if it is not met. */
		if pOrderBy != 0 {
			ii = 0
			for {
				if !(ii < (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr) {
					break
				}
				pExpr = (*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(ii)*20))).FpExpr
				if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) != int32(TK_COLUMN) {
					return
				}
				if (*TExpr)(unsafe.Pointer(pExpr)).FiTable != iCsr {
					return
				}
				if libc.Int32FromUint8((*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(ii)*20))).Ffg.FsortFlags)&int32(KEYINFO_ORDER_BIGNULL) != 0 {
					return
				}
				goto _2
			_2:
				;
				ii = ii + 1
			}
		}
		/* All conditions are met. Add the terms to the where-clause object. */
		if (*TSelect)(unsafe.Pointer(p)).FiOffset != 0 && (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Compound) == uint32(0) {
			_whereAddLimitExpr(tls, pWC, (*TSelect)(unsafe.Pointer(p)).FiOffset, (*TExpr)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpLimit)).FpRight, iCsr, int32(SQLITE_INDEX_CONSTRAINT_OFFSET))
		}
		if (*TSelect)(unsafe.Pointer(p)).FiOffset == 0 || (*TSelect)(unsafe.Pointer(p)).FselFlags&uint32(SF_Compound) == uint32(0) {
			_whereAddLimitExpr(tls, pWC, (*TSelect)(unsafe.Pointer(p)).FiLimit, (*TExpr)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpLimit)).FpLeft, iCsr, int32(SQLITE_INDEX_CONSTRAINT_LIMIT))
		}
	}
}

// C documentation
//
//	/*
//	** Deallocate a WhereClause structure.  The WhereClause structure
//	** itself is not freed.  This routine is the inverse of
//	** sqlite3WhereClauseInit().
//	*/
func _sqlite3WhereClauseClear(tls *libc.TLS, pWC uintptr) {
	var a, aLast, db uintptr
	_, _, _ = a, aLast, db
	db = (*TParse)(unsafe.Pointer((*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpParse)).Fdb
	if (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm > 0 {
		a = (*TWhereClause)(unsafe.Pointer(pWC)).Fa
		aLast = (*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr((*TWhereClause)(unsafe.Pointer(pWC)).FnTerm-int32(1))*48
		for int32(1) != 0 {
			if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(a)).FwtFlags)&int32(TERM_DYNAMIC) != 0 {
				_sqlite3ExprDelete(tls, db, (*TWhereTerm)(unsafe.Pointer(a)).FpExpr)
			}
			if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(a)).FwtFlags)&(libc.Int32FromInt32(TERM_ORINFO)|libc.Int32FromInt32(TERM_ANDINFO)) != 0 {
				if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(a)).FwtFlags)&int32(TERM_ORINFO) != 0 {
					_whereOrInfoDelete(tls, db, *(*uintptr)(unsafe.Pointer(&(*TWhereTerm)(unsafe.Pointer(a)).Fu)))
				} else {
					_whereAndInfoDelete(tls, db, *(*uintptr)(unsafe.Pointer(&(*TWhereTerm)(unsafe.Pointer(a)).Fu)))
				}
			}
			if a == aLast {
				break
			}
			a += 48
		}
	}
}

// C documentation
//
//	/*
//	** These routines walk (recursively) an expression tree and generate
//	** a bitmask indicating which tables are used in that expression
//	** tree.
//	**
//	** sqlite3WhereExprUsage(MaskSet, Expr) ->
//	**
//	**       Return a Bitmask of all tables referenced by Expr.  Expr can be
//	**       be NULL, in which case 0 is returned.
//	**
//	** sqlite3WhereExprUsageNN(MaskSet, Expr) ->
//	**
//	**       Same as sqlite3WhereExprUsage() except that Expr must not be
//	**       NULL.  The "NN" suffix on the name stands for "Not Null".
//	**
//	** sqlite3WhereExprListUsage(MaskSet, ExprList) ->
//	**
//	**       Return a Bitmask of all tables referenced by every expression
//	**       in the expression list ExprList.  ExprList can be NULL, in which
//	**       case 0 is returned.
//	**
//	** sqlite3WhereExprUsageFull(MaskSet, ExprList) ->
//	**
//	**       Internal use only.  Called only by sqlite3WhereExprUsageNN() for
//	**       complex expressions that require pushing register values onto
//	**       the stack.  Many calls to sqlite3WhereExprUsageNN() do not need
//	**       the more complex analysis done by this routine.  Hence, the
//	**       computations done by this routine are broken out into a separate
//	**       "no-inline" function to avoid the stack push overhead in the
//	**       common case where it is not needed.
//	*/
func _sqlite3WhereExprUsageFull(tls *libc.TLS, pMaskSet uintptr, p uintptr) (r TBitmask) {
	var mask TBitmask
	var v1 uint64
	_, _ = mask, v1
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_IF_NULL_ROW) {
		v1 = _sqlite3WhereGetMask(tls, pMaskSet, (*TExpr)(unsafe.Pointer(p)).FiTable)
	} else {
		v1 = uint64(0)
	}
	mask = v1
	if (*TExpr)(unsafe.Pointer(p)).FpLeft != 0 {
		mask = mask | _sqlite3WhereExprUsageNN(tls, pMaskSet, (*TExpr)(unsafe.Pointer(p)).FpLeft)
	}
	if (*TExpr)(unsafe.Pointer(p)).FpRight != 0 {
		mask = mask | _sqlite3WhereExprUsageNN(tls, pMaskSet, (*TExpr)(unsafe.Pointer(p)).FpRight)
	} else {
		if (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
			if (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_VarSelect)) != uint32(0) {
				(*TWhereMaskSet)(unsafe.Pointer(pMaskSet)).FbVarSelect = int32(1)
			}
			mask = mask | _exprSelectUsage(tls, pMaskSet, *(*uintptr)(unsafe.Pointer(p + 20)))
		} else {
			if *(*uintptr)(unsafe.Pointer(p + 20)) != 0 {
				mask = mask | _sqlite3WhereExprListUsage(tls, pMaskSet, *(*uintptr)(unsafe.Pointer(p + 20)))
			}
		}
	}
	if (libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_FUNCTION) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_AGG_FUNCTION)) && (*TExpr)(unsafe.Pointer(p)).Fflags&uint32(EP_WinFunc) != uint32(0) {
		mask = mask | _sqlite3WhereExprListUsage(tls, pMaskSet, (*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(p)).Fy)))).FpPartition)
		mask = mask | _sqlite3WhereExprListUsage(tls, pMaskSet, (*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(p)).Fy)))).FpOrderBy)
		mask = mask | _sqlite3WhereExprUsage(tls, pMaskSet, (*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer(p)).Fy)))).FpFilter)
	}
	return mask
}

// C documentation
//
//	/*
//	** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
//	** where X is a reference to the iColumn of table iCur or of index pIdx
//	** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
//	** the op parameter.  Return a pointer to the term.  Return 0 if not found.
//	**
//	** If pIdx!=0 then it must be one of the indexes of table iCur.
//	** Search for terms matching the iColumn-th column of pIdx
//	** rather than the iColumn-th column of table iCur.
//	**
//	** The term returned might by Y=<expr> if there is another constraint in
//	** the WHERE clause that specifies that X=Y.  Any such constraints will be
//	** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
//	** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
//	** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
//	** other equivalent values.  Hence a search for X will return <expr> if X=A1
//	** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
//	**
//	** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
//	** then try for the one with no dependencies on <expr> - in other words where
//	** <expr> is a constant expression of some kind.  Only return entries of
//	** the form "X <op> Y" where Y is a column in another table if no terms of
//	** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
//	** exist, try to return a term that does not use WO_EQUIV.
//	*/
func _sqlite3WhereFindTerm(tls *libc.TLS, pWC uintptr, iCur int32, iColumn int32, notReady TBitmask, op Tu32, pIdx uintptr) (r uintptr) {
	bp := tls.Alloc(96)
	defer tls.Free(96)
	var p, pResult uintptr
	var _ /* scan at bp+0 */ TWhereScan
	_, _ = p, pResult
	pResult = uintptr(0)
	p = _whereScanInit(tls, bp, pWC, iCur, iColumn, op, pIdx)
	op = op & libc.Uint32FromInt32(libc.Int32FromInt32(WO_EQ)|libc.Int32FromInt32(WO_IS))
	for p != 0 {
		if (*TWhereTerm)(unsafe.Pointer(p)).FprereqRight&notReady == uint64(0) {
			if (*TWhereTerm)(unsafe.Pointer(p)).FprereqRight == uint64(0) && uint32((*TWhereTerm)(unsafe.Pointer(p)).FeOperator)&op != uint32(0) {
				return p
			}
			if pResult == uintptr(0) {
				pResult = p
			}
		}
		p = _whereScanNext(tls, bp)
	}
	return pResult
}

// C documentation
//
//	/*
//	** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
//	** operate directly on the rowids returned by a WHERE clause.  Return
//	** ONEPASS_SINGLE (1) if the statement can operation directly because only
//	** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
//	** optimization can be used on multiple
//	**
//	** If the ONEPASS optimization is used (if this routine returns true)
//	** then also write the indices of open cursors used by ONEPASS
//	** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
//	** table and iaCur[1] gets the cursor used by an auxiliary index.
//	** Either value may be -1, indicating that cursor is not used.
//	** Any cursors returned will have been opened for writing.
//	**
//	** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
//	** unable to use the ONEPASS optimization.
//	*/
func _sqlite3WhereOkOnePass(tls *libc.TLS, pWInfo uintptr, aiCur uintptr) (r int32) {
	libc.Xmemcpy(tls, aiCur, pWInfo+20, libc.Uint32FromInt64(4)*libc.Uint32FromInt32(2))
	return libc.Int32FromUint8((*TWhereInfo)(unsafe.Pointer(pWInfo)).FeOnePass)
}

// C documentation
//
//	/*
//	** sqlite3WhereBegin() has already been called for the SELECT statement
//	** passed as the second argument when this function is invoked. It generates
//	** code to populate the Window.regResult register for each window function
//	** and invoke the sub-routine at instruction addrGosub once for each row.
//	** sqlite3WhereEnd() is always called before returning.
//	**
//	** This function handles several different types of window frames, which
//	** require slightly different processing. The following pseudo code is
//	** used to implement window frames of the form:
//	**
//	**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
//	**
//	** Other window frame types use variants of the following:
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**       if( new partition ){
//	**         Gosub flush
//	**       }
//	**       Insert new row into eph table.
//	**
//	**       if( first row of partition ){
//	**         // Rewind three cursors, all open on the eph table.
//	**         Rewind(csrEnd);
//	**         Rewind(csrStart);
//	**         Rewind(csrCurrent);
//	**
//	**         regEnd = <expr2>          // FOLLOWING expression
//	**         regStart = <expr1>        // PRECEDING expression
//	**       }else{
//	**         // First time this branch is taken, the eph table contains two
//	**         // rows. The first row in the partition, which all three cursors
//	**         // currently point to, and the following row.
//	**         AGGSTEP
//	**         if( (regEnd--)<=0 ){
//	**           RETURN_ROW
//	**           if( (regStart--)<=0 ){
//	**             AGGINVERSE
//	**           }
//	**         }
//	**       }
//	**     }
//	**     flush:
//	**       AGGSTEP
//	**       while( 1 ){
//	**         RETURN ROW
//	**         if( csrCurrent is EOF ) break;
//	**         if( (regStart--)<=0 ){
//	**           AggInverse(csrStart)
//	**           Next(csrStart)
//	**         }
//	**       }
//	**
//	** The pseudo-code above uses the following shorthand:
//	**
//	**   AGGSTEP:    invoke the aggregate xStep() function for each window function
//	**               with arguments read from the current row of cursor csrEnd, then
//	**               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
//	**
//	**   RETURN_ROW: return a row to the caller based on the contents of the
//	**               current row of csrCurrent and the current state of all
//	**               aggregates. Then step cursor csrCurrent forward one row.
//	**
//	**   AGGINVERSE: invoke the aggregate xInverse() function for each window
//	**               functions with arguments read from the current row of cursor
//	**               csrStart. Then step csrStart forward one row.
//	**
//	** There are two other ROWS window frames that are handled significantly
//	** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
//	** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
//	** cases because they change the order in which the three cursors (csrStart,
//	** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
//	** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
//	** three.
//	**
//	**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**       if( new partition ){
//	**         Gosub flush
//	**       }
//	**       Insert new row into eph table.
//	**       if( first row of partition ){
//	**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**         regEnd = <expr2>
//	**         regStart = <expr1>
//	**       }else{
//	**         if( (regEnd--)<=0 ){
//	**           AGGSTEP
//	**         }
//	**         RETURN_ROW
//	**         if( (regStart--)<=0 ){
//	**           AGGINVERSE
//	**         }
//	**       }
//	**     }
//	**     flush:
//	**       if( (regEnd--)<=0 ){
//	**         AGGSTEP
//	**       }
//	**       RETURN_ROW
//	**
//	**
//	**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
//	**
//	**   ... loop started by sqlite3WhereBegin() ...
//	**     if( new partition ){
//	**       Gosub flush
//	**     }
//	**     Insert new row into eph table.
//	**     if( first row of partition ){
//	**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**       regEnd = <expr2>
//	**       regStart = regEnd - <expr1>
//	**     }else{
//	**       AGGSTEP
//	**       if( (regEnd--)<=0 ){
//	**         RETURN_ROW
//	**       }
//	**       if( (regStart--)<=0 ){
//	**         AGGINVERSE
//	**       }
//	**     }
//	**   }
//	**   flush:
//	**     AGGSTEP
//	**     while( 1 ){
//	**       if( (regEnd--)<=0 ){
//	**         RETURN_ROW
//	**         if( eof ) break;
//	**       }
//	**       if( (regStart--)<=0 ){
//	**         AGGINVERSE
//	**         if( eof ) break
//	**       }
//	**     }
//	**     while( !eof csrCurrent ){
//	**       RETURN_ROW
//	**     }
//	**
//	** For the most part, the patterns above are adapted to support UNBOUNDED by
//	** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
//	** CURRENT ROW by assuming that it is equivalent to "0 PRECEDING/FOLLOWING".
//	** This is optimized of course - branches that will never be taken and
//	** conditions that are always true are omitted from the VM code. The only
//	** exceptional case is:
//	**
//	**   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**     if( new partition ){
//	**       Gosub flush
//	**     }
//	**     Insert new row into eph table.
//	**     if( first row of partition ){
//	**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**       regStart = <expr1>
//	**     }else{
//	**       AGGSTEP
//	**     }
//	**   }
//	**   flush:
//	**     AGGSTEP
//	**     while( 1 ){
//	**       if( (regStart--)<=0 ){
//	**         AGGINVERSE
//	**         if( eof ) break
//	**       }
//	**       RETURN_ROW
//	**     }
//	**     while( !eof csrCurrent ){
//	**       RETURN_ROW
//	**     }
//	**
//	** Also requiring special handling are the cases:
//	**
//	**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
//	**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
//	**
//	** when (expr1 < expr2). This is detected at runtime, not by this function.
//	** To handle this case, the pseudo-code programs depicted above are modified
//	** slightly to be:
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**     if( new partition ){
//	**       Gosub flush
//	**     }
//	**     Insert new row into eph table.
//	**     if( first row of partition ){
//	**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**       regEnd = <expr2>
//	**       regStart = <expr1>
//	**       if( regEnd < regStart ){
//	**         RETURN_ROW
//	**         delete eph table contents
//	**         continue
//	**       }
//	**     ...
//	**
//	** The new "continue" statement in the above jumps to the next iteration
//	** of the outer loop - the one started by sqlite3WhereBegin().
//	**
//	** The various GROUPS cases are implemented using the same patterns as
//	** ROWS. The VM code is modified slightly so that:
//	**
//	**   1. The else branch in the main loop is only taken if the row just
//	**      added to the ephemeral table is the start of a new group. In
//	**      other words, it becomes:
//	**
//	**         ... loop started by sqlite3WhereBegin() ...
//	**         if( new partition ){
//	**           Gosub flush
//	**         }
//	**         Insert new row into eph table.
//	**         if( first row of partition ){
//	**           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**           regEnd = <expr2>
//	**           regStart = <expr1>
//	**         }else if( new group ){
//	**           ...
//	**         }
//	**       }
//	**
//	**   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
//	**      AGGINVERSE step processes the current row of the relevant cursor and
//	**      all subsequent rows belonging to the same group.
//	**
//	** RANGE window frames are a little different again. As for GROUPS, the
//	** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
//	** deal in groups instead of rows. As for ROWS and GROUPS, there are three
//	** basic cases:
//	**
//	**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**       if( new partition ){
//	**         Gosub flush
//	**       }
//	**       Insert new row into eph table.
//	**       if( first row of partition ){
//	**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**         regEnd = <expr2>
//	**         regStart = <expr1>
//	**       }else{
//	**         AGGSTEP
//	**         while( (csrCurrent.key + regEnd) < csrEnd.key ){
//	**           RETURN_ROW
//	**           while( csrStart.key + regStart) < csrCurrent.key ){
//	**             AGGINVERSE
//	**           }
//	**         }
//	**       }
//	**     }
//	**     flush:
//	**       AGGSTEP
//	**       while( 1 ){
//	**         RETURN ROW
//	**         if( csrCurrent is EOF ) break;
//	**           while( csrStart.key + regStart) < csrCurrent.key ){
//	**             AGGINVERSE
//	**           }
//	**         }
//	**       }
//	**
//	** In the above notation, "csr.key" means the current value of the ORDER BY
//	** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
//	** or <expr PRECEDING) read from cursor csr.
//	**
//	**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**       if( new partition ){
//	**         Gosub flush
//	**       }
//	**       Insert new row into eph table.
//	**       if( first row of partition ){
//	**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**         regEnd = <expr2>
//	**         regStart = <expr1>
//	**       }else{
//	**         while( (csrEnd.key + regEnd) <= csrCurrent.key ){
//	**           AGGSTEP
//	**         }
//	**         while( (csrStart.key + regStart) < csrCurrent.key ){
//	**           AGGINVERSE
//	**         }
//	**         RETURN_ROW
//	**       }
//	**     }
//	**     flush:
//	**       while( (csrEnd.key + regEnd) <= csrCurrent.key ){
//	**         AGGSTEP
//	**       }
//	**       while( (csrStart.key + regStart) < csrCurrent.key ){
//	**         AGGINVERSE
//	**       }
//	**       RETURN_ROW
//	**
//	**   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
//	**
//	**     ... loop started by sqlite3WhereBegin() ...
//	**       if( new partition ){
//	**         Gosub flush
//	**       }
//	**       Insert new row into eph table.
//	**       if( first row of partition ){
//	**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
//	**         regEnd = <expr2>
//	**         regStart = <expr1>
//	**       }else{
//	**         AGGSTEP
//	**         while( (csrCurrent.key + regEnd) < csrEnd.key ){
//	**           while( (csrCurrent.key + regStart) > csrStart.key ){
//	**             AGGINVERSE
//	**           }
//	**           RETURN_ROW
//	**         }
//	**       }
//	**     }
//	**     flush:
//	**       AGGSTEP
//	**       while( 1 ){
//	**         while( (csrCurrent.key + regStart) > csrStart.key ){
//	**           AGGINVERSE
//	**           if( eof ) break "while( 1 )" loop.
//	**         }
//	**         RETURN_ROW
//	**       }
//	**       while( !eof csrCurrent ){
//	**         RETURN_ROW
//	**       }
//	**
//	** The text above leaves out many details. Refer to the code and comments
//	** below for a more complete picture.
//	*/
func _sqlite3WindowCodeStep(tls *libc.TLS, pParse uintptr, p uintptr, pWInfo uintptr, regGosub int32, addrGosub int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var addr, addr1, addrBreak, addrBreak1, addrBreak2, addrBreak3, addrEmpty, addrGe, addrGosubFlush, addrInteger, addrNe, addrNext, addrStart, addrStart1, bRPS, bRPS1, csrInput, csrWrite, iInput, lbl, lbl1, lblWhereEnd, nInput, nPart, nPeer, op, regEnd, regFlushPart, regNew, regNewPart, regNewPeer, regPeer, regRecord, regStart, v1 int32
	var pKeyInfo, pMWin, pOrderBy, pPart, v, v2 uintptr
	var _ /* s at bp+0 */ TWindowCodeArg
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addr, addr1, addrBreak, addrBreak1, addrBreak2, addrBreak3, addrEmpty, addrGe, addrGosubFlush, addrInteger, addrNe, addrNext, addrStart, addrStart1, bRPS, bRPS1, csrInput, csrWrite, iInput, lbl, lbl1, lblWhereEnd, nInput, nPart, nPeer, op, pKeyInfo, pMWin, pOrderBy, pPart, regEnd, regFlushPart, regNew, regNewPart, regNewPeer, regPeer, regRecord, regStart, v, v1, v2
	pMWin = (*TSelect)(unsafe.Pointer(p)).FpWin
	pOrderBy = (*TWindow)(unsafe.Pointer(pMWin)).FpOrderBy
	v = _sqlite3GetVdbe(tls, pParse)                                                                                                /* Cursor used to write to eph. table */
	csrInput = (*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8))).FiCursor                                     /* Cursor of sub-select */
	nInput = int32((*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer((*TSelect)(unsafe.Pointer(p)).FpSrc + 8))).FpSTab)).FnCol) /* Address of OP_Ne */
	addrGosubFlush = 0                                                                                                              /* Address of OP_Gosub to flush: */
	addrInteger = 0                                                                                                                 /* regNew array in record form */
	regNewPeer = 0                                                                                                                  /* Peer values for new row (part of regNew) */
	regPeer = 0                                                                                                                     /* Peer values for current row */
	regFlushPart = 0                                                                                                                /* Label just before sqlite3WhereEnd() code */
	regStart = 0                                                                                                                    /* Value of <expr> PRECEDING */
	regEnd = 0                                                                                                                      /* Value of <expr> FOLLOWING */
	lblWhereEnd = _sqlite3VdbeMakeLabel(tls, pParse)
	/* Fill in the context object */
	libc.Xmemset(tls, bp, 0, uint32(56))
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FpParse = pParse
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FpMWin = pMWin
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FpVdbe = v
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FregGosub = regGosub
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FaddrGosub = addrGosub
	(**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr = (*TWindow)(unsafe.Pointer(pMWin)).FiEphCsr
	csrWrite = (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr + int32(1)
	(**(**TWindowCodeArg)(__ccgo_up(bp))).Fstart.Fcsr = (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr + int32(2)
	(**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Fcsr = (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr + int32(3)
	/* Figure out when rows may be deleted from the ephemeral table. There
	 ** are four options - they may never be deleted (eDelete==0), they may
	 ** be deleted as soon as they are no longer part of the window frame
	 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
	 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
	 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
	switch libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) {
	case int32(TK_FOLLOWING):
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) != int32(TK_RANGE) && _windowExprGtZero(tls, pParse, (*TWindow)(unsafe.Pointer(pMWin)).FpStart) != 0 {
			(**(**TWindowCodeArg)(__ccgo_up(bp))).FeDelete = int32(WINDOW_RETURN_ROW)
		}
	case int32(TK_UNBOUNDED):
		if _windowCacheFrame(tls, pMWin) == 0 {
			if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_PRECEDING) {
				if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) != int32(TK_RANGE) && _windowExprGtZero(tls, pParse, (*TWindow)(unsafe.Pointer(pMWin)).FpEnd) != 0 {
					(**(**TWindowCodeArg)(__ccgo_up(bp))).FeDelete = int32(WINDOW_AGGSTEP)
				}
			} else {
				(**(**TWindowCodeArg)(__ccgo_up(bp))).FeDelete = int32(WINDOW_RETURN_ROW)
			}
		}
	default:
		(**(**TWindowCodeArg)(__ccgo_up(bp))).FeDelete = int32(WINDOW_AGGINVERSE)
		break
	}
	/* Allocate registers for the array of values from the sub-query, the
	 ** same values in record form, and the rowid used to insert said record
	 ** into the ephemeral table.  */
	regNew = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
	**(**int32)(__ccgo_up(pParse + 48)) += nInput
	v2 = pParse + 48
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	v1 = *(*int32)(unsafe.Pointer(v2))
	regRecord = v1
	v2 = pParse + 48
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	v1 = *(*int32)(unsafe.Pointer(v2))
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FregRowid = v1
	/* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
	 ** clause, allocate registers to store the results of evaluating each
	 ** <expr>.  */
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_PRECEDING) || libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_FOLLOWING) {
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		regStart = v1
	}
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_PRECEDING) || libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_FOLLOWING) {
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		regEnd = v1
	}
	/* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
	 ** registers to store copies of the ORDER BY expressions (peer values)
	 ** for the main loop, and for each cursor (start, current and end). */
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) != int32(TK_ROWS) {
		if pOrderBy != 0 {
			v1 = (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr
		} else {
			v1 = 0
		}
		nPeer = v1
		regNewPeer = regNew + (*TWindow)(unsafe.Pointer(pMWin)).FnBufferCol
		if (*TWindow)(unsafe.Pointer(pMWin)).FpPartition != 0 {
			regNewPeer = regNewPeer + (*TExprList)(unsafe.Pointer((*TWindow)(unsafe.Pointer(pMWin)).FpPartition)).FnExpr
		}
		regPeer = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += nPeer
		(**(**TWindowCodeArg)(__ccgo_up(bp))).Fstart.Freg = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += nPeer
		(**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Freg = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += nPeer
		(**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Freg = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
		**(**int32)(__ccgo_up(pParse + 48)) += nPeer
	}
	/* Load the column values for the row returned by the sub-select
	 ** into an array of registers starting at regNew. Assemble them into
	 ** a record in register regRecord. */
	iInput = 0
	for {
		if !(iInput < nInput) {
			break
		}
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), csrInput, iInput, regNew+iInput)
		goto _10
	_10:
		;
		iInput = iInput + 1
	}
	_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), regNew, nInput, regRecord)
	/* An input row has just been read into an array of registers starting
	 ** at regNew. If the window has a PARTITION clause, this block generates
	 ** VM code to check if the input row is the start of a new partition.
	 ** If so, it does an OP_Gosub to an address to be filled in later. The
	 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
	if (*TWindow)(unsafe.Pointer(pMWin)).FpPartition != 0 {
		pPart = (*TWindow)(unsafe.Pointer(pMWin)).FpPartition
		nPart = (*TExprList)(unsafe.Pointer(pPart)).FnExpr
		regNewPart = regNew + (*TWindow)(unsafe.Pointer(pMWin)).FnBufferCol
		pKeyInfo = _sqlite3KeyInfoFromExprList(tls, pParse, pPart, 0, 0)
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		regFlushPart = v1
		addr = _sqlite3VdbeAddOp3(tls, v, int32(OP_Compare), regNewPart, (*TWindow)(unsafe.Pointer(pMWin)).FregPart, nPart)
		_sqlite3VdbeAppendP4(tls, v, pKeyInfo, -int32(9))
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Jump), addr+int32(2), addr+int32(4), addr+int32(2))
		addrGosubFlush = _sqlite3VdbeAddOp1(tls, v, int32(OP_Gosub), regFlushPart)
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Copy), regNewPart, (*TWindow)(unsafe.Pointer(pMWin)).FregPart, nPart-int32(1))
	}
	/* Insert the new row into the ephemeral table */
	_sqlite3VdbeAddOp2(tls, v, int32(OP_NewRowid), csrWrite, (**(**TWindowCodeArg)(__ccgo_up(bp))).FregRowid)
	_sqlite3VdbeAddOp3(tls, v, int32(OP_Insert), csrWrite, regRecord, (**(**TWindowCodeArg)(__ccgo_up(bp))).FregRowid)
	addrNe = _sqlite3VdbeAddOp3(tls, v, int32(OP_Ne), (*TWindow)(unsafe.Pointer(pMWin)).FregOne, 0, (**(**TWindowCodeArg)(__ccgo_up(bp))).FregRowid)
	/* This block is run for the first row of each partition */
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FregArg = _windowInitAccum(tls, pParse, pMWin)
	if regStart != 0 {
		_sqlite3ExprCode(tls, pParse, (*TWindow)(unsafe.Pointer(pMWin)).FpStart, regStart)
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE) {
			v1 = int32(3)
		} else {
			v1 = 0
		}
		_windowCheckValue(tls, pParse, regStart, 0+v1)
	}
	if regEnd != 0 {
		_sqlite3ExprCode(tls, pParse, (*TWindow)(unsafe.Pointer(pMWin)).FpEnd, regEnd)
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE) {
			v1 = int32(3)
		} else {
			v1 = 0
		}
		_windowCheckValue(tls, pParse, regEnd, int32(1)+v1)
	}
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) != int32(TK_RANGE) && libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) && regStart != 0 {
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_FOLLOWING) {
			v1 = int32(OP_Ge)
		} else {
			v1 = int32(OP_Le)
		}
		op = v1
		addrGe = _sqlite3VdbeAddOp3(tls, v, op, regStart, 0, regEnd)
		/* NeverNull because bound <expr> */
		/*   values previously checked */
		_windowAggFinal(tls, bp, 0)
		_sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr)
		_windowReturnOneRow(tls, bp)
		_sqlite3VdbeAddOp1(tls, v, int32(OP_ResetSorter), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr)
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, lblWhereEnd)
		_sqlite3VdbeJumpHere(tls, v, addrGe)
	}
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_FOLLOWING) && libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) != int32(TK_RANGE) && regEnd != 0 {
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Subtract), regStart, regEnd, regStart)
	}
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) != int32(TK_UNBOUNDED) {
		_sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fstart.Fcsr)
	}
	_sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr)
	_sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Fcsr)
	if regPeer != 0 && pOrderBy != 0 {
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Copy), regNewPeer, regPeer, (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr-int32(1))
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Copy), regPeer, (**(**TWindowCodeArg)(__ccgo_up(bp))).Fstart.Freg, (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr-int32(1))
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Copy), regPeer, (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Freg, (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr-int32(1))
		_sqlite3VdbeAddOp3(tls, v, int32(OP_Copy), regPeer, (**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Freg, (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr-int32(1))
	}
	_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, lblWhereEnd)
	_sqlite3VdbeJumpHere(tls, v, addrNe)
	/* Beginning of the block executed for the second and subsequent rows. */
	if regPeer != 0 {
		_windowIfNewPeer(tls, pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd)
	}
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_FOLLOWING) {
		_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), 0, 0)
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) != int32(TK_UNBOUNDED) {
			if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE) {
				lbl = _sqlite3VdbeMakeLabel(tls, pParse)
				addrNext = _sqlite3VdbeCurrentAddr(tls, v)
				_windowCodeRangeTest(tls, bp, int32(OP_Ge), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr, regEnd, (**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Fcsr, lbl)
				_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
				_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, 0)
				_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, addrNext)
				_sqlite3VdbeResolveLabel(tls, v, lbl)
			} else {
				_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), regEnd, 0)
				_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
			}
		}
	} else {
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_PRECEDING) {
			bRPS = libc.BoolInt32(libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_PRECEDING) && libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE))
			_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), regEnd, 0)
			if bRPS != 0 {
				_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
			}
			_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, 0)
			if !(bRPS != 0) {
				_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
			}
		} else {
			addr1 = 0
			_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), 0, 0)
			if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) != int32(TK_UNBOUNDED) {
				if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE) {
					lbl1 = 0
					addr1 = _sqlite3VdbeCurrentAddr(tls, v)
					if regEnd != 0 {
						lbl1 = _sqlite3VdbeMakeLabel(tls, pParse)
						_windowCodeRangeTest(tls, bp, int32(OP_Ge), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr, regEnd, (**(**TWindowCodeArg)(__ccgo_up(bp))).Fend.Fcsr, lbl1)
					}
					_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, 0)
					_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
					if regEnd != 0 {
						_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, addr1)
						_sqlite3VdbeResolveLabel(tls, v, lbl1)
					}
				} else {
					if regEnd != 0 {
						addr1 = _sqlite3VdbeAddOp3(tls, v, int32(OP_IfPos), regEnd, 0, int32(1))
					}
					_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, 0)
					_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
					if regEnd != 0 {
						_sqlite3VdbeJumpHere(tls, v, addr1)
					}
				}
			}
		}
	}
	/* End of the main input loop */
	_sqlite3VdbeResolveLabel(tls, v, lblWhereEnd)
	_sqlite3WhereEnd(tls, pWInfo)
	/* Fall through */
	if (*TWindow)(unsafe.Pointer(pMWin)).FpPartition != 0 {
		addrInteger = _sqlite3VdbeAddOp2(tls, v, int32(OP_Integer), 0, regFlushPart)
		_sqlite3VdbeJumpHere(tls, v, addrGosubFlush)
	}
	(**(**TWindowCodeArg)(__ccgo_up(bp))).FregRowid = 0
	addrEmpty = _sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), csrWrite)
	if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_PRECEDING) {
		bRPS1 = libc.BoolInt32(libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_PRECEDING) && libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE))
		_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), regEnd, 0)
		if bRPS1 != 0 {
			_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
		}
		_windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, 0)
	} else {
		if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeStart) == int32(TK_FOLLOWING) {
			_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), 0, 0)
			if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeFrmType) == int32(TK_RANGE) {
				addrStart = _sqlite3VdbeCurrentAddr(tls, v)
				addrBreak2 = _windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, int32(1))
				addrBreak1 = _windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, int32(1))
			} else {
				if libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pMWin)).FeEnd) == int32(TK_UNBOUNDED) {
					addrStart = _sqlite3VdbeCurrentAddr(tls, v)
					addrBreak1 = _windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), regStart, int32(1))
					addrBreak2 = _windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), 0, int32(1))
				} else {
					/* assert( regStart>=0 );
					 ** regEnd = regEnd - regStart;
					 ** regStart = 0;   */
					_sqlite3VdbeAddOp3(tls, v, int32(OP_Subtract), regStart, regEnd, regEnd)
					_sqlite3VdbeAddOp2(tls, v, int32(OP_Integer), 0, regStart)
					addrStart = _sqlite3VdbeCurrentAddr(tls, v)
					addrBreak1 = _windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), regEnd, int32(1))
					addrBreak2 = _windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, int32(1))
				}
			}
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, addrStart)
			_sqlite3VdbeJumpHere(tls, v, addrBreak2)
			addrStart = _sqlite3VdbeCurrentAddr(tls, v)
			addrBreak3 = _windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, int32(1))
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, addrStart)
			_sqlite3VdbeJumpHere(tls, v, addrBreak1)
			_sqlite3VdbeJumpHere(tls, v, addrBreak3)
		} else {
			_windowCodeOp(tls, bp, int32(WINDOW_AGGSTEP), 0, 0)
			addrStart1 = _sqlite3VdbeCurrentAddr(tls, v)
			addrBreak = _windowCodeOp(tls, bp, int32(WINDOW_RETURN_ROW), 0, int32(1))
			_windowCodeOp(tls, bp, int32(WINDOW_AGGINVERSE), regStart, 0)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Goto), 0, addrStart1)
			_sqlite3VdbeJumpHere(tls, v, addrBreak)
		}
	}
	_sqlite3VdbeJumpHere(tls, v, addrEmpty)
	_sqlite3VdbeAddOp1(tls, v, int32(OP_ResetSorter), (**(**TWindowCodeArg)(__ccgo_up(bp))).Fcurrent.Fcsr)
	if (*TWindow)(unsafe.Pointer(pMWin)).FpPartition != 0 {
		if (*TWindow)(unsafe.Pointer(pMWin)).FregStartRowid != 0 {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Integer), int32(1), (*TWindow)(unsafe.Pointer(pMWin)).FregStartRowid)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Integer), 0, (*TWindow)(unsafe.Pointer(pMWin)).FregEndRowid)
		}
		_sqlite3VdbeChangeP1(tls, v, addrInteger, _sqlite3VdbeCurrentAddr(tls, v))
		_sqlite3VdbeAddOp1(tls, v, int32(OP_Return), regFlushPart)
	}
}

/************** End of window.c **********************************************/
/************** Begin file parse.c *******************************************/
/* This file is automatically generated by Lemon from input grammar
** source file "parse.y".
 */
/*
** 2001-09-15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains SQLite's SQL parser.
**
** The canonical source code to this file ("parse.y") is a Lemon grammar
** file that specifies the input grammar and actions to take while parsing.
** That input file is processed by Lemon to generate a C-language
** implementation of a parser for the given grammar.  You might be reading
** this comment as part of the translated C-code.  Edits should be made
** to the original parse.y sources.
 */

/* #include "sqliteInt.h" */

/*
** Verify that the pParse->isCreate field is set
 */

/*
** Disable all error recovery processing in the parser push-down
** automaton.
 */

/*
** Make yytestcase() the same as testcase()
 */

/*
** Indicate that sqlite3ParserFree() will never be called with a null
** pointer.
 */

/*
** In the amalgamation, the parse.c file generated by lemon and the
** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
** has access to the the size of the yyParser object and so the parser
** engine can be allocated from stack.  In that case, only the
** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
** omitted.
 */

/*
** Alternative datatype for the argument to the malloc() routine passed
** into sqlite3ParserAlloc().  The default is size_t.
 */

// C documentation
//
//	/*
//	** Register those built-in window functions that are not also aggregates.
//	*/
func _sqlite3WindowFunctions(tls *libc.TLS) {
	_sqlite3InsertBuiltinFuncs(tls, uintptr(unsafe.Pointer(&_aWindowFuncs)), libc.Int32FromUint32(libc.Uint32FromInt64(600)/libc.Uint32FromInt64(40)))
}

// C documentation
//
//	/*
//	** Create and return a deep copy of the object passed as the second
//	** argument. If an OOM condition is encountered, NULL is returned
//	** and the db->mallocFailed flag set.
//	*/
func _sqlite3WithDup(tls *libc.TLS, db uintptr, p uintptr) (r uintptr) {
	var i int32
	var nByte Tsqlite3_int64
	var pRet uintptr
	_, _, _ = i, nByte, pRet
	pRet = uintptr(0)
	if p != 0 {
		nByte = libc.Int64FromUint32(uint32(libc.UintptrFromInt32(0)+12) + libc.Uint32FromInt32((*TWith)(unsafe.Pointer(p)).FnCte)*libc.Uint32FromInt64(24))
		pRet = _sqlite3DbMallocZero(tls, db, libc.Uint64FromInt64(nByte))
		if pRet != 0 {
			(*TWith)(unsafe.Pointer(pRet)).FnCte = (*TWith)(unsafe.Pointer(p)).FnCte
			i = 0
			for {
				if !(i < (*TWith)(unsafe.Pointer(p)).FnCte) {
					break
				}
				(*(*TCte)(unsafe.Pointer(pRet + 12 + uintptr(i)*24))).FpSelect = _sqlite3SelectDup(tls, db, (*(*TCte)(unsafe.Pointer(p + 12 + uintptr(i)*24))).FpSelect, 0)
				(*(*TCte)(unsafe.Pointer(pRet + 12 + uintptr(i)*24))).FpCols = _sqlite3ExprListDup(tls, db, (*(*TCte)(unsafe.Pointer(p + 12 + uintptr(i)*24))).FpCols, 0)
				(*(*TCte)(unsafe.Pointer(pRet + 12 + uintptr(i)*24))).FzName = _sqlite3DbStrDup(tls, db, (*(*TCte)(unsafe.Pointer(p + 12 + uintptr(i)*24))).FzName)
				(*(*TCte)(unsafe.Pointer(pRet + 12 + uintptr(i)*24))).FeM10d = (*(*TCte)(unsafe.Pointer(p + 12 + uintptr(i)*24))).FeM10d
				goto _1
			_1:
				;
				i = i + 1
			}
		}
	}
	return pRet
}

// C documentation
//
//	/*
//	** This routine implements a busy callback that sleeps and tries
//	** again until a timeout value is reached.  The timeout value is
//	** an integer number of milliseconds passed in as the first
//	** argument.
//	**
//	** Return non-zero to retry the lock.  Return zero to stop trying
//	** and cause SQLite to return SQLITE_BUSY.
//	*/
func _sqliteDefaultBusyCallback(tls *libc.TLS, ptr uintptr, count int32) (r int32) {
	var db uintptr
	var delay, prior, tmout int32
	_, _, _, _ = db, delay, prior, tmout
	db = ptr
	tmout = (*Tsqlite3)(unsafe.Pointer(db)).FbusyTimeout
	if count < libc.Int32FromUint32(libc.Uint32FromInt64(12)/libc.Uint32FromInt64(1)) {
		delay = libc.Int32FromUint8(_delays[count])
		prior = libc.Int32FromUint8(_totals[count])
	} else {
		delay = libc.Int32FromUint8(_delays[libc.Int32FromUint32(libc.Uint32FromInt64(12)/libc.Uint32FromInt64(1))-libc.Int32FromInt32(1)])
		prior = libc.Int32FromUint8(_totals[libc.Int32FromUint32(libc.Uint32FromInt64(12)/libc.Uint32FromInt64(1))-libc.Int32FromInt32(1)]) + delay*(count-(libc.Int32FromUint32(libc.Uint32FromInt64(12)/libc.Uint32FromInt64(1))-libc.Int32FromInt32(1)))
	}
	if prior+delay > tmout {
		delay = tmout - prior
		if delay <= 0 {
			return 0
		}
	}
	_sqlite3OsSleep(tls, (*Tsqlite3)(unsafe.Pointer(db)).FpVfs, delay*int32(1000))
	return int32(1)
}

// C documentation
//
//	/*
//	** Clear the column names from every VIEW in database idx.
//	*/
func _sqliteViewResetAll(tls *libc.TLS, db uintptr, idx int32) {
	var i, pTab, v2 uintptr
	_, _, _ = i, pTab, v2
	if !(libc.Int32FromUint16((*TSchema)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(idx)*16))).FpSchema)).FschemaFlags)&libc.Int32FromInt32(DB_UnresetViews) == libc.Int32FromInt32(DB_UnresetViews)) {
		return
	}
	i = (*THash)(unsafe.Pointer((**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(idx)*16))).FpSchema + 8)).Ffirst
	for {
		if !(i != 0) {
			break
		}
		pTab = (*THashElem)(unsafe.Pointer(i)).Fdata
		if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VIEW) {
			_sqlite3DeleteColumnNames(tls, db, pTab)
		}
		goto _1
	_1:
		;
		i = (*THashElem)(unsafe.Pointer(i)).Fnext
	}
	v2 = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(idx)*16))).FpSchema + 78
	*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) & ^libc.Int32FromInt32(DB_UnresetViews))
}

// C documentation
//
//	/*
//	** Attempt to extract a value from pExpr and use it to construct *ppVal.
//	**
//	** If pAlloc is not NULL, then an UnpackedRecord object is created for
//	** pAlloc if one does not exist and the new value is added to the
//	** UnpackedRecord object.
//	**
//	** A value is extracted in the following cases:
//	**
//	**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
//	**
//	**  * The expression is a bound variable, and this is a reprepare, or
//	**
//	**  * The expression is a literal value.
//	**
//	** On success, *ppVal is made to point to the extracted value.  The caller
//	** is responsible for ensuring that the value is eventually freed.
//	*/
func _stat4ValueFromExpr(tls *libc.TLS, pParse uintptr, pExpr uintptr, affinity Tu8, pAlloc uintptr, ppVal uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, v, v1 uintptr
	var iBindVar, rc int32
	var _ /* pVal at bp+0 */ uintptr
	_, _, _, _, _ = db, iBindVar, rc, v, v1
	rc = SQLITE_OK
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	/* Skip over any TK_COLLATE nodes */
	pExpr = _sqlite3ExprSkipCollate(tls, pExpr)
	if !(pExpr != 0) {
		**(**uintptr)(__ccgo_up(bp)) = _valueNew(tls, db, pAlloc)
		if **(**uintptr)(__ccgo_up(bp)) != 0 {
			_sqlite3VdbeMemSetNull(tls, **(**uintptr)(__ccgo_up(bp)))
		}
	} else {
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_VARIABLE) && (*Tsqlite3)(unsafe.Pointer(db)).Fflags&uint64(SQLITE_EnableQPSG) == uint64(0) {
			iBindVar = int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn)
			_sqlite3VdbeSetVarmask(tls, (*TParse)(unsafe.Pointer(pParse)).FpVdbe, iBindVar)
			v1 = (*TParse)(unsafe.Pointer(pParse)).FpReprepare
			v = v1
			if v1 != uintptr(0) {
				**(**uintptr)(__ccgo_up(bp)) = _valueNew(tls, db, pAlloc)
				if **(**uintptr)(__ccgo_up(bp)) != 0 {
					rc = _sqlite3VdbeMemCopy(tls, **(**uintptr)(__ccgo_up(bp)), (*TVdbe)(unsafe.Pointer(v)).FaVar+uintptr(iBindVar-int32(1))*40)
					_sqlite3ValueApplyAffinity(tls, **(**uintptr)(__ccgo_up(bp)), affinity, (*Tsqlite3)(unsafe.Pointer(db)).Fenc)
					(*Tsqlite3_value)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp)))).Fdb = (*TParse)(unsafe.Pointer(pParse)).Fdb
				}
			}
		} else {
			rc = _valueFromExpr(tls, db, pExpr, (*Tsqlite3)(unsafe.Pointer(db)).Fenc, affinity, bp, pAlloc)
		}
	}
	**(**uintptr)(__ccgo_up(ppVal)) = **(**uintptr)(__ccgo_up(bp))
	return rc
}

func _statColumn(tls *libc.TLS, pCursor uintptr, ctx uintptr, i int32) (r int32) {
	var db, pCsr uintptr
	var iDb int32
	_, _, _ = db, iDb, pCsr
	pCsr = pCursor
	switch i {
	case 0: /* name */
		Xsqlite3_result_text(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FzName, -int32(1), uintptr(-libc.Int32FromInt32(1)))
	case int32(1): /* path */
		if !((*TStatCursor)(unsafe.Pointer(pCsr)).FisAgg != 0) {
			Xsqlite3_result_text(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FzPath, -int32(1), uintptr(-libc.Int32FromInt32(1)))
		}
	case int32(2): /* pageno */
		if (*TStatCursor)(unsafe.Pointer(pCsr)).FisAgg != 0 {
			Xsqlite3_result_int64(tls, ctx, int64((*TStatCursor)(unsafe.Pointer(pCsr)).FnPage))
		} else {
			Xsqlite3_result_int64(tls, ctx, libc.Int64FromUint32((*TStatCursor)(unsafe.Pointer(pCsr)).FiPageno))
		}
	case int32(3): /* pagetype */
		if !((*TStatCursor)(unsafe.Pointer(pCsr)).FisAgg != 0) {
			Xsqlite3_result_text(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FzPagetype, -int32(1), libc.UintptrFromInt32(0))
		}
	case int32(4): /* ncell */
		Xsqlite3_result_int64(tls, ctx, int64((*TStatCursor)(unsafe.Pointer(pCsr)).FnCell))
	case int32(5): /* payload */
		Xsqlite3_result_int64(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FnPayload)
	case int32(6): /* unused */
		Xsqlite3_result_int64(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FnUnused)
	case int32(7): /* mx_payload */
		Xsqlite3_result_int64(tls, ctx, int64((*TStatCursor)(unsafe.Pointer(pCsr)).FnMxPayload))
	case int32(8): /* pgoffset */
		if !((*TStatCursor)(unsafe.Pointer(pCsr)).FisAgg != 0) {
			Xsqlite3_result_int64(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FiOffset)
		}
	case int32(9): /* pgsize */
		Xsqlite3_result_int64(tls, ctx, (*TStatCursor)(unsafe.Pointer(pCsr)).FszPage)
	case int32(10): /* schema */
		db = Xsqlite3_context_db_handle(tls, ctx)
		iDb = (*TStatCursor)(unsafe.Pointer(pCsr)).FiDb
		Xsqlite3_result_text(tls, ctx, (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer(db)).FaDb + uintptr(iDb)*16))).FzDbSName, -int32(1), libc.UintptrFromInt32(0))
	default: /* aggregate */
		Xsqlite3_result_int(tls, ctx, libc.Int32FromUint8((*TStatCursor)(unsafe.Pointer(pCsr)).FisAgg))
		break
	}
	return SQLITE_OK
}

// C documentation
//
//	/* Populate the StatPage object with information about the all
//	** cells found on the page currently under analysis.
//	*/
func _statDecodePage(tls *libc.TLS, pBt uintptr, p uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var aData, aHdr, pCell uintptr
	var i, iNext, iOff, isLeaf, j, nHdr, nLocal, nOvfl, nUnused, nUsable, rc, szPage, v1 int32
	var iPrev Tu32
	var v2 uint32
	var _ /* dummy at bp+8 */ Tu64
	var _ /* nPayload at bp+0 */ Tu32
	var _ /* pPg at bp+16 */ uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aData, aHdr, i, iNext, iOff, iPrev, isLeaf, j, nHdr, nLocal, nOvfl, nUnused, nUsable, pCell, rc, szPage, v1, v2
	aData = (*TStatPage)(unsafe.Pointer(p)).FaPg
	if (*TStatPage)(unsafe.Pointer(p)).FiPgno == uint32(1) {
		v1 = int32(100)
	} else {
		v1 = 0
	}
	aHdr = aData + uintptr(v1)
	(*TStatPage)(unsafe.Pointer(p)).Fflags = **(**Tu8)(__ccgo_up(aHdr))
	if libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x0A) || libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x0D) {
		isLeaf = int32(1)
		nHdr = int32(8)
	} else {
		if libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x05) || libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x02) {
			isLeaf = 0
			nHdr = int32(12)
		} else {
			goto statPageIsCorrupt
		}
	}
	if (*TStatPage)(unsafe.Pointer(p)).FiPgno == uint32(1) {
		nHdr = nHdr + int32(100)
	}
	(*TStatPage)(unsafe.Pointer(p)).FnCell = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 3)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 3 + 1)))
	(*TStatPage)(unsafe.Pointer(p)).FnMxPayload = 0
	szPage = _sqlite3BtreeGetPageSize(tls, pBt)
	nUnused = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 5)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 5 + 1))) - nHdr - int32(2)*(*TStatPage)(unsafe.Pointer(p)).FnCell
	nUnused = nUnused + libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 7)))
	iOff = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 1)))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aHdr + 1 + 1)))
	for iOff != 0 {
		if iOff >= szPage {
			goto statPageIsCorrupt
		}
		nUnused = nUnused + (libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(iOff+int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(iOff+int32(2)) + 1))))
		iNext = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(iOff))))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(iOff) + 1)))
		if iNext < iOff+int32(4) && iNext > 0 {
			goto statPageIsCorrupt
		}
		iOff = iNext
	}
	(*TStatPage)(unsafe.Pointer(p)).FnUnused = nUnused
	if isLeaf != 0 {
		v2 = uint32(0)
	} else {
		v2 = _sqlite3Get4byte(tls, aHdr+8)
	}
	(*TStatPage)(unsafe.Pointer(p)).FiRightChildPg = v2
	if (*TStatPage)(unsafe.Pointer(p)).FnCell != 0 { /* Usable bytes per page */
		_sqlite3BtreeEnter(tls, pBt)
		nUsable = szPage - _sqlite3BtreeGetReserveNoMutex(tls, pBt)
		_sqlite3BtreeLeave(tls, pBt)
		(*TStatPage)(unsafe.Pointer(p)).FaCell = Xsqlite3_malloc64(tls, uint64(libc.Uint32FromInt32((*TStatPage)(unsafe.Pointer(p)).FnCell+libc.Int32FromInt32(1))*uint32(24)))
		if (*TStatPage)(unsafe.Pointer(p)).FaCell == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, (*TStatPage)(unsafe.Pointer(p)).FaCell, 0, libc.Uint32FromInt32((*TStatPage)(unsafe.Pointer(p)).FnCell+libc.Int32FromInt32(1))*uint32(24))
		i = 0
		for {
			if !(i < (*TStatPage)(unsafe.Pointer(p)).FnCell) {
				break
			}
			pCell = (*TStatPage)(unsafe.Pointer(p)).FaCell + uintptr(i)*24
			iOff = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(nHdr+i*int32(2)))))<<int32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(nHdr+i*int32(2)) + 1)))
			if iOff < nHdr || iOff >= szPage {
				goto statPageIsCorrupt
			}
			if !(isLeaf != 0) {
				(*TStatCell)(unsafe.Pointer(pCell)).FiChildPg = _sqlite3Get4byte(tls, aData+uintptr(iOff))
				iOff = iOff + int32(4)
			}
			if libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x05) {
				/* A table interior node. nPayload==0. */
			} else { /* Bytes of payload stored locally */
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aData + uintptr(iOff)))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
					**(**Tu32)(__ccgo_up(bp)) = uint32(**(**Tu8)(__ccgo_up(aData + uintptr(iOff))))
					v1 = libc.Int32FromInt32(1)
				} else {
					v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aData+uintptr(iOff), bp))
				}
				iOff = iOff + libc.Int32FromUint8(libc.Uint8FromInt32(v1))
				if libc.Int32FromUint8((*TStatPage)(unsafe.Pointer(p)).Fflags) == int32(0x0D) {
					iOff = iOff + libc.Int32FromUint8(_sqlite3GetVarint(tls, aData+uintptr(iOff), bp+8))
				}
				if **(**Tu32)(__ccgo_up(bp)) > libc.Uint32FromInt32((*TStatPage)(unsafe.Pointer(p)).FnMxPayload) {
					(*TStatPage)(unsafe.Pointer(p)).FnMxPayload = libc.Int32FromUint32(**(**Tu32)(__ccgo_up(bp)))
				}
				nLocal = _getLocalPayload(tls, nUsable, (*TStatPage)(unsafe.Pointer(p)).Fflags, libc.Int32FromUint32(**(**Tu32)(__ccgo_up(bp))))
				if nLocal < 0 {
					goto statPageIsCorrupt
				}
				(*TStatCell)(unsafe.Pointer(pCell)).FnLocal = nLocal
				if **(**Tu32)(__ccgo_up(bp)) > libc.Uint32FromInt32(nLocal) {
					nOvfl = libc.Int32FromUint32((**(**Tu32)(__ccgo_up(bp)) - libc.Uint32FromInt32(nLocal) + libc.Uint32FromInt32(nUsable) - uint32(4) - uint32(1)) / libc.Uint32FromInt32(nUsable-libc.Int32FromInt32(4)))
					if iOff+nLocal+int32(4) > nUsable || **(**Tu32)(__ccgo_up(bp)) > uint32(0x7fffffff) {
						goto statPageIsCorrupt
					}
					(*TStatCell)(unsafe.Pointer(pCell)).FnLastOvfl = libc.Int32FromUint32(**(**Tu32)(__ccgo_up(bp)) - libc.Uint32FromInt32(nLocal) - libc.Uint32FromInt32((nOvfl-int32(1))*(nUsable-int32(4))))
					(*TStatCell)(unsafe.Pointer(pCell)).FnOvfl = nOvfl
					(*TStatCell)(unsafe.Pointer(pCell)).FaOvfl = Xsqlite3_malloc64(tls, uint64(uint32(4)*libc.Uint32FromInt32(nOvfl)))
					if (*TStatCell)(unsafe.Pointer(pCell)).FaOvfl == uintptr(0) {
						return int32(SQLITE_NOMEM)
					}
					**(**Tu32)(__ccgo_up((*TStatCell)(unsafe.Pointer(pCell)).FaOvfl)) = _sqlite3Get4byte(tls, aData+uintptr(iOff+nLocal))
					j = int32(1)
					for {
						if !(j < nOvfl) {
							break
						}
						iPrev = **(**Tu32)(__ccgo_up((*TStatCell)(unsafe.Pointer(pCell)).FaOvfl + uintptr(j-int32(1))*4))
						**(**uintptr)(__ccgo_up(bp + 16)) = uintptr(0)
						rc = _sqlite3PagerGet(tls, _sqlite3BtreePager(tls, pBt), iPrev, bp+16, 0)
						if rc != SQLITE_OK {
							return rc
						}
						**(**Tu32)(__ccgo_up((*TStatCell)(unsafe.Pointer(pCell)).FaOvfl + uintptr(j)*4)) = _sqlite3Get4byte(tls, _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp + 16))))
						_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp + 16)))
						goto _5
					_5:
						;
						j = j + 1
					}
				}
			}
			goto _3
		_3:
			;
			i = i + 1
		}
	}
	return SQLITE_OK
	goto statPageIsCorrupt
statPageIsCorrupt:
	;
	(*TStatPage)(unsafe.Pointer(p)).Fflags = uint8(0)
	_statClearCells(tls, p)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Load a copy of the page data for page iPg into the buffer belonging
//	** to page object pPg. Allocate the buffer if necessary. Return SQLITE_OK
//	** if successful, or an SQLite error code otherwise.
//	*/
func _statGetPage(tls *libc.TLS, pBt uintptr, iPg Tu32, pPg uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var a uintptr
	var pgsz, rc int32
	var _ /* pDbPage at bp+0 */ uintptr
	_, _, _ = a, pgsz, rc
	pgsz = _sqlite3BtreeGetPageSize(tls, pBt)
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	if (*TStatPage)(unsafe.Pointer(pPg)).FaPg == uintptr(0) {
		(*TStatPage)(unsafe.Pointer(pPg)).FaPg = Xsqlite3_malloc(tls, pgsz+int32(DBSTAT_PAGE_PADDING_BYTES))
		if (*TStatPage)(unsafe.Pointer(pPg)).FaPg == uintptr(0) {
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, (*TStatPage)(unsafe.Pointer(pPg)).FaPg+uintptr(pgsz), 0, uint32(DBSTAT_PAGE_PADDING_BYTES))
	}
	rc = _sqlite3PagerGet(tls, _sqlite3BtreePager(tls, pBt), iPg, bp, 0)
	if rc == SQLITE_OK {
		a = _sqlite3PagerGetData(tls, **(**uintptr)(__ccgo_up(bp)))
		libc.Xmemcpy(tls, (*TStatPage)(unsafe.Pointer(pPg)).FaPg, a, libc.Uint32FromInt32(pgsz))
		_sqlite3PagerUnref(tls, **(**uintptr)(__ccgo_up(bp)))
	}
	return rc
}

func _statResetCsr(tls *libc.TLS, pCsr uintptr) {
	var i int32
	_ = i
	/* In some circumstances, specifically if an OOM has occurred, the call
	 ** to sqlite3_reset() may cause the pager to be reset (emptied). It is
	 ** important that statClearPage() is called to free any page refs before
	 ** this happens. dbsqlfuzz 9ed3e4e3816219d3509d711636c38542bf3f40b1. */
	i = 0
	for {
		if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(1280)/libc.Uint32FromInt64(40))) {
			break
		}
		_statClearPage(tls, pCsr+16+uintptr(i)*40)
		Xsqlite3_free(tls, (**(**TStatPage)(__ccgo_up(pCsr + 16 + uintptr(i)*40))).FaPg)
		(**(**TStatPage)(__ccgo_up(pCsr + 16 + uintptr(i)*40))).FaPg = uintptr(0)
		goto _1
	_1:
		;
		i = i + 1
	}
	Xsqlite3_reset(tls, (*TStatCursor)(unsafe.Pointer(pCsr)).FpStmt)
	(*TStatCursor)(unsafe.Pointer(pCsr)).FiPage = 0
	Xsqlite3_free(tls, (*TStatCursor)(unsafe.Pointer(pCsr)).FzPath)
	(*TStatCursor)(unsafe.Pointer(pCsr)).FzPath = uintptr(0)
	(*TStatCursor)(unsafe.Pointer(pCsr)).FisEof = uint8(0)
}

// C documentation
//
//	/*
//	** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
//	** the current value of pCsr->iPageno.
//	*/
func _statSizeAndOffset(tls *libc.TLS, pCsr uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var fd, pBt, pPager, pTab uintptr
	var _ /* x at bp+0 */ [2]Tsqlite3_int64
	_, _, _, _ = fd, pBt, pPager, pTab
	pTab = (*Tsqlite3_vtab_cursor)(unsafe.Pointer(pCsr)).FpVtab
	pBt = (**(**TDb)(__ccgo_up((*Tsqlite3)(unsafe.Pointer((*TStatTable)(unsafe.Pointer(pTab)).Fdb)).FaDb + uintptr((*TStatTable)(unsafe.Pointer(pTab)).FiDb)*16))).FpBt
	pPager = _sqlite3BtreePager(tls, pBt)
	/* If connected to a ZIPVFS backend, find the page size and
	 ** offset from ZIPVFS.
	 */
	fd = _sqlite3PagerFile(tls, pPager)
	(**(**[2]Tsqlite3_int64)(__ccgo_up(bp)))[0] = libc.Int64FromUint32((*TStatCursor)(unsafe.Pointer(pCsr)).FiPageno)
	if _sqlite3OsFileControl(tls, fd, int32(230440), bp) == SQLITE_OK {
		(*TStatCursor)(unsafe.Pointer(pCsr)).FiOffset = (**(**[2]Tsqlite3_int64)(__ccgo_up(bp)))[0]
		**(**Ti64)(__ccgo_up(pCsr + 1352)) += (**(**[2]Tsqlite3_int64)(__ccgo_up(bp)))[int32(1)]
	} else {
		/* Not ZIPVFS: The default page size and offset */
		**(**Ti64)(__ccgo_up(pCsr + 1352)) += int64(_sqlite3BtreeGetPageSize(tls, pBt))
		(*TStatCursor)(unsafe.Pointer(pCsr)).FiOffset = (*TStatCursor)(unsafe.Pointer(pCsr)).FszPage * libc.Int64FromUint32((*TStatCursor)(unsafe.Pointer(pCsr)).FiPageno-libc.Uint32FromInt32(1))
	}
}

// C documentation
//
//	/*
//	** Sync the journal. In other words, make sure all the pages that have
//	** been written to the journal have actually reached the surface of the
//	** disk and can be restored in the event of a hot-journal rollback.
//	**
//	** If the Pager.noSync flag is set, then this function is a no-op.
//	** Otherwise, the actions required depend on the journal-mode and the
//	** device characteristics of the file-system, as follows:
//	**
//	**   * If the journal file is an in-memory journal file, no action need
//	**     be taken.
//	**
//	**   * Otherwise, if the device does not support the SAFE_APPEND property,
//	**     then the nRec field of the most recently written journal header
//	**     is updated to contain the number of journal records that have
//	**     been written following it. If the pager is operating in full-sync
//	**     mode, then the journal file is synced before this field is updated.
//	**
//	**   * If the device does not support the SEQUENTIAL property, then
//	**     journal file is synced.
//	**
//	** Or, in pseudo-code:
//	**
//	**   if( NOT <in-memory journal> ){
//	**     if( NOT SAFE_APPEND ){
//	**       if( <full-sync mode> ) xSync(<journal file>);
//	**       <update nRec field>
//	**     }
//	**     if( NOT SEQUENTIAL ) xSync(<journal file>);
//	**   }
//	**
//	** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
//	** page currently held in memory before returning SQLITE_OK. If an IO
//	** error is encountered, then the IO error code is returned to the caller.
//	*/
func _syncJournal(tls *libc.TLS, pPager uintptr, newHdr int32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var iDc, rc, v1 int32
	var iNextHdrOffset Ti64
	var _ /* aMagic at bp+0 */ [8]Tu8
	var _ /* zHeader at bp+8 */ [12]Tu8
	_, _, _, _ = iDc, iNextHdrOffset, rc, v1 /* Return code */
	rc = _sqlite3PagerExclusiveLock(tls, pPager)
	if rc != SQLITE_OK {
		return rc
	}
	if !((*TPager)(unsafe.Pointer(pPager)).FnoSync != 0) {
		if (*Tsqlite3_file)(unsafe.Pointer((*TPager)(unsafe.Pointer(pPager)).Fjfd)).FpMethods != uintptr(0) && libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FjournalMode) != int32(PAGER_JOURNALMODE_MEMORY) {
			iDc = _sqlite3OsDeviceCharacteristics(tls, (*TPager)(unsafe.Pointer(pPager)).Ffd)
			if 0 == iDc&int32(SQLITE_IOCAP_SAFE_APPEND) {
				libc.Xmemcpy(tls, bp+8, uintptr(unsafe.Pointer(&_aJournalMagic)), uint32(8))
				_sqlite3Put4byte(tls, bp+8+uintptr(8), libc.Uint32FromInt32((*TPager)(unsafe.Pointer(pPager)).FnRec))
				iNextHdrOffset = _journalHdrOffset(tls, pPager)
				rc = _sqlite3OsRead(tls, (*TPager)(unsafe.Pointer(pPager)).Fjfd, bp, int32(8), iNextHdrOffset)
				if rc == SQLITE_OK && 0 == libc.Xmemcmp(tls, bp, uintptr(unsafe.Pointer(&_aJournalMagic)), uint32(8)) {
					rc = _sqlite3OsWrite(tls, (*TPager)(unsafe.Pointer(pPager)).Fjfd, uintptr(unsafe.Pointer(&_zerobyte)), int32(1), iNextHdrOffset)
				}
				if rc != SQLITE_OK && rc != libc.Int32FromInt32(SQLITE_IOERR)|libc.Int32FromInt32(2)<<libc.Int32FromInt32(8) {
					return rc
				}
				/* Write the nRec value into the journal file header. If in
				 ** full-synchronous mode, sync the journal first. This ensures that
				 ** all data has really hit the disk before nRec is updated to mark
				 ** it as a candidate for rollback.
				 **
				 ** This is not required if the persistent media supports the
				 ** SAFE_APPEND property. Because in this case it is not possible
				 ** for garbage data to be appended to the file, the nRec field
				 ** is populated with 0xFFFFFFFF when the journal header is written
				 ** and never needs to be updated.
				 */
				if (*TPager)(unsafe.Pointer(pPager)).FfullSync != 0 && 0 == iDc&int32(SQLITE_IOCAP_SEQUENTIAL) {
					rc = _sqlite3OsSync(tls, (*TPager)(unsafe.Pointer(pPager)).Fjfd, libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FsyncFlags))
					if rc != SQLITE_OK {
						return rc
					}
				}
				rc = _sqlite3OsWrite(tls, (*TPager)(unsafe.Pointer(pPager)).Fjfd, bp+8, int32(12), (*TPager)(unsafe.Pointer(pPager)).FjournalHdr)
				if rc != SQLITE_OK {
					return rc
				}
			}
			if 0 == iDc&int32(SQLITE_IOCAP_SEQUENTIAL) {
				if libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FsyncFlags) == int32(SQLITE_SYNC_FULL) {
					v1 = int32(SQLITE_SYNC_DATAONLY)
				} else {
					v1 = 0
				}
				rc = _sqlite3OsSync(tls, (*TPager)(unsafe.Pointer(pPager)).Fjfd, libc.Int32FromUint8((*TPager)(unsafe.Pointer(pPager)).FsyncFlags)|v1)
				if rc != SQLITE_OK {
					return rc
				}
			}
			(*TPager)(unsafe.Pointer(pPager)).FjournalHdr = (*TPager)(unsafe.Pointer(pPager)).FjournalOff
			if newHdr != 0 && 0 == iDc&int32(SQLITE_IOCAP_SAFE_APPEND) {
				(*TPager)(unsafe.Pointer(pPager)).FnRec = 0
				rc = _writeJournalHdr(tls, pPager)
				if rc != SQLITE_OK {
					return rc
				}
			}
		} else {
			(*TPager)(unsafe.Pointer(pPager)).FjournalHdr = (*TPager)(unsafe.Pointer(pPager)).FjournalOff
		}
	}
	/* Unless the pager is in noSync mode, the journal file was just
	 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
	 ** all pages.
	 */
	_sqlite3PcacheClearSyncFlags(tls, (*TPager)(unsafe.Pointer(pPager)).FpPCache)
	(*TPager)(unsafe.Pointer(pPager)).FeState = uint8(PAGER_WRITER_DBMOD)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
//	** table that has a column named zCol.  The search is left-to-right.
//	** The first match found is returned.
//	**
//	** When found, set *piTab and *piCol to the table index and column index
//	** of the matching column and return TRUE.
//	**
//	** If not found, return FALSE.
//	*/
func _tableAndColumnIndex(tls *libc.TLS, pSrc uintptr, iStart int32, iEnd int32, zCol uintptr, piTab uintptr, piCol uintptr, bIgnoreHidden int32) (r int32) {
	var i, iCol int32
	_, _ = i, iCol /* Index of column matching zCol */
	/* Both or neither are NULL */
	i = iStart
	for {
		if !(i <= iEnd) {
			break
		}
		iCol = _sqlite3ColumnIndex(tls, (*(*TSrcItem)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48))).FpSTab, zCol)
		if iCol >= 0 && (bIgnoreHidden == 0 || libc.BoolInt32(libc.Int32FromUint16((*TColumn)(unsafe.Pointer((*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer(pSrc + 8 + uintptr(i)*48))).FpSTab)).FaCol+uintptr(iCol)*12)).FcolFlags)&int32(COLFLAG_HIDDEN) != 0) == 0) {
			if piTab != 0 {
				_sqlite3SrcItemColumnUsed(tls, pSrc+8+uintptr(i)*48, iCol)
				**(**int32)(__ccgo_up(piTab)) = i
				**(**int32)(__ccgo_up(piCol)) = iCol
			}
			return int32(1)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return 0
}

// C documentation
//
//	/*
//	** If the pBase expression originated in the ON or USING clause of
//	** a join, then transfer the appropriate markings over to derived.
//	*/
func _transferJoinMarkings(tls *libc.TLS, pDerived uintptr, pBase uintptr) {
	if pDerived != 0 && (*TExpr)(unsafe.Pointer(pBase)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON)) != uint32(0) {
		**(**Tu32)(__ccgo_up(pDerived + 4)) |= (*TExpr)(unsafe.Pointer(pBase)).Fflags & libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)|libc.Int32FromInt32(EP_InnerON))
		*(*int32)(unsafe.Pointer(pDerived + 36)) = *(*int32)(unsafe.Pointer(pBase + 36))
	}
}

// C documentation
//
//	/*
//	** Convert OP_Column opcodes to OP_Copy in previously generated code.
//	**
//	** This routine runs over generated VDBE code and translates OP_Column
//	** opcodes into OP_Copy when the table is being accessed via co-routine
//	** instead of via table lookup.
//	**
//	** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
//	** cursor iTabCur are transformed into OP_Sequence opcode for the
//	** iAutoidxCur cursor, in order to generate unique rowids for the
//	** automatic index being generated.
//	*/
func _translateColumnToCopy(tls *libc.TLS, pParse uintptr, iStart int32, iTabCur int32, iRegister int32, iAutoidxCur int32) {
	var iEnd int32
	var pOp, v uintptr
	_, _, _ = iEnd, pOp, v
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	pOp = _sqlite3VdbeGetOp(tls, v, iStart)
	iEnd = _sqlite3VdbeCurrentAddr(tls, v)
	if (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FmallocFailed != 0 {
		return
	}
	for {
		if !(iStart < iEnd) {
			break
		}
		if (*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 != iTabCur {
			goto _1
		}
		if libc.Int32FromUint8((*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode) == int32(OP_Column) {
			(*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode = uint8(OP_Copy)
			(*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 = (*TVdbeOp)(unsafe.Pointer(pOp)).Fp2 + iRegister
			(*TVdbeOp)(unsafe.Pointer(pOp)).Fp2 = (*TVdbeOp)(unsafe.Pointer(pOp)).Fp3
			(*TVdbeOp)(unsafe.Pointer(pOp)).Fp3 = 0
			(*TVdbeOp)(unsafe.Pointer(pOp)).Fp5 = uint16(2) /* Cause the MEM_Subtype flag to be cleared */
		} else {
			if libc.Int32FromUint8((*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode) == int32(OP_Rowid) {
				(*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode = uint8(OP_Sequence)
				(*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 = iAutoidxCur
			}
		}
		goto _1
	_1:
		;
		iStart = iStart + 1
		pOp += 20
	}
}

/*
** Two routines for printing the content of an sqlite3_index_info
** structure.  Used for testing and debugging only.  If neither
** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
** are no-ops.
 */

// C documentation
//
//	/*
//	** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
//	** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
//	*/
func _trimFunc(tls *libc.TLS, context uintptr, argc int32, argv uintptr) {
	var aLen, azChar, z, zCharSet, zIn, v1 uintptr
	var flags, i, nChar int32
	var len1, len11, nIn uint32
	_, _, _, _, _, _, _, _, _, _, _, _ = aLen, azChar, flags, i, len1, len11, nChar, nIn, z, zCharSet, zIn, v1 /* Loop counter */
	aLen = uintptr(0)                                                                                          /* Length of each character in zCharSet */
	azChar = uintptr(0)                                                                                        /* Number of characters in zCharSet */
	if Xsqlite3_value_type(tls, **(**uintptr)(__ccgo_up(argv))) == int32(SQLITE_NULL) {
		return
	}
	zIn = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv)))
	if zIn == uintptr(0) {
		return
	}
	nIn = libc.Uint32FromInt32(Xsqlite3_value_bytes(tls, **(**uintptr)(__ccgo_up(argv))))
	if argc == int32(1) {
		nChar = int32(1)
		aLen = uintptr(unsafe.Pointer(&_lenOne))
		azChar = uintptr(unsafe.Pointer(&_azOne))
		zCharSet = uintptr(0)
	} else {
		v1 = Xsqlite3_value_text(tls, **(**uintptr)(__ccgo_up(argv + 1*4)))
		zCharSet = v1
		if v1 == uintptr(0) {
			return
		} else {
			z = zCharSet
			nChar = libc.Int32FromInt32(0)
			for {
				if !(**(**uint8)(__ccgo_up(z)) != 0) {
					break
				}
				v1 = z
				z = z + 1
				if libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))) >= int32(0xc0) {
					for libc.Int32FromUint8(**(**uint8)(__ccgo_up(z)))&int32(0xc0) == int32(0x80) {
						z = z + 1
					}
				}
				goto _2
			_2:
				;
				nChar = nChar + 1
			}
			if nChar > 0 {
				azChar = _contextMalloc(tls, context, int64(nChar)*libc.Int64FromUint32(libc.Uint32FromInt64(4)+libc.Uint32FromInt64(4)))
				if azChar == uintptr(0) {
					return
				}
				aLen = azChar + uintptr(nChar)*4
				z = zCharSet
				nChar = libc.Int32FromInt32(0)
				for {
					if !(**(**uint8)(__ccgo_up(z)) != 0) {
						break
					}
					**(**uintptr)(__ccgo_up(azChar + uintptr(nChar)*4)) = z
					v1 = z
					z = z + 1
					if libc.Int32FromUint8(**(**uint8)(__ccgo_up(v1))) >= int32(0xc0) {
						for libc.Int32FromUint8(**(**uint8)(__ccgo_up(z)))&int32(0xc0) == int32(0x80) {
							z = z + 1
						}
					}
					**(**uint32)(__ccgo_up(aLen + uintptr(nChar)*4)) = libc.Uint32FromInt32(int32(z) - int32(**(**uintptr)(__ccgo_up(azChar + uintptr(nChar)*4))))
					goto _4
				_4:
					;
					nChar = nChar + 1
				}
			}
		}
	}
	if nChar > 0 {
		flags = int32(Xsqlite3_user_data(tls, context))
		if flags&int32(1) != 0 {
			for nIn > uint32(0) {
				len1 = uint32(0)
				i = 0
				for {
					if !(i < nChar) {
						break
					}
					len1 = **(**uint32)(__ccgo_up(aLen + uintptr(i)*4))
					if len1 <= nIn && libc.Xmemcmp(tls, zIn, **(**uintptr)(__ccgo_up(azChar + uintptr(i)*4)), len1) == 0 {
						break
					}
					goto _6
				_6:
					;
					i = i + 1
				}
				if i >= nChar {
					break
				}
				zIn = zIn + uintptr(len1)
				nIn = nIn - len1
			}
		}
		if flags&int32(2) != 0 {
			for nIn > uint32(0) {
				len11 = uint32(0)
				i = 0
				for {
					if !(i < nChar) {
						break
					}
					len11 = **(**uint32)(__ccgo_up(aLen + uintptr(i)*4))
					if len11 <= nIn && libc.Xmemcmp(tls, zIn+uintptr(nIn-len11), **(**uintptr)(__ccgo_up(azChar + uintptr(i)*4)), len11) == 0 {
						break
					}
					goto _7
				_7:
					;
					i = i + 1
				}
				if i >= nChar {
					break
				}
				nIn = nIn - len11
			}
		}
		if zCharSet != 0 {
			Xsqlite3_free(tls, azChar)
		}
	}
	Xsqlite3_result_text(tls, context, zIn, libc.Int32FromUint32(nIn), uintptr(-libc.Int32FromInt32(1)))
}

// C documentation
//
//	/*
//	** Return the value of a system call.  Return NULL if zName is not a
//	** recognized system call name.  NULL is also returned if the system call
//	** is currently undefined.
//	*/
func _unixGetSystemCall(tls *libc.TLS, pNotUsed uintptr, zName uintptr) (r Tsqlite3_syscall_ptr) {
	var i uint32
	_ = i
	_ = pNotUsed
	i = uint32(0)
	for {
		if !(i < libc.Uint32FromInt64(348)/libc.Uint32FromInt64(12)) {
			break
		}
		if libc.Xstrcmp(tls, zName, _aSyscall[i].FzName) == 0 {
			return _aSyscall[i].FpCurrent
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	return uintptr(0)
}

// C documentation
//
//	/*
//	** If *pArg is initially negative then this is a query.  Set *pArg to
//	** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
//	**
//	** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
//	*/
func _unixModeBit(tls *libc.TLS, pFile uintptr, mask uint8, pArg uintptr) {
	var v1 uintptr
	_ = v1
	if **(**int32)(__ccgo_up(pArg)) < 0 {
		**(**int32)(__ccgo_up(pArg)) = libc.BoolInt32(libc.Int32FromUint16((*TunixFile)(unsafe.Pointer(pFile)).FctrlFlags)&libc.Int32FromUint8(mask) != 0)
	} else {
		if **(**int32)(__ccgo_up(pArg)) == 0 {
			v1 = pFile + 18
			*(*uint16)(unsafe.Pointer(v1)) = uint16(int32(*(*uint16)(unsafe.Pointer(v1))) & ^libc.Int32FromUint8(mask))
		} else {
			v1 = pFile + 18
			*(*uint16)(unsafe.Pointer(v1)) = uint16(int32(*(*uint16)(unsafe.Pointer(v1))) | libc.Int32FromUint8(mask))
		}
	}
}

// C documentation
//
//	/*
//	** Return the name of the first system call after zName.  If zName==NULL
//	** then return the name of the first system call.  Return NULL if zName
//	** is the last system call or if zName is not the name of a valid
//	** system call.
//	*/
func _unixNextSystemCall(tls *libc.TLS, p uintptr, zName uintptr) (r uintptr) {
	var i int32
	_ = i
	i = -int32(1)
	_ = p
	if zName != 0 {
		i = 0
		for {
			if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(348)/libc.Uint32FromInt64(12))-libc.Int32FromInt32(1)) {
				break
			}
			if libc.Xstrcmp(tls, zName, _aSyscall[i].FzName) == 0 {
				break
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	i = i + 1
	for {
		if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(348)/libc.Uint32FromInt64(12))) {
			break
		}
		if _aSyscall[i].FpCurrent != uintptr(0) {
			return _aSyscall[i].FzName
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	return uintptr(0)
}

/*
** Do not accept any file descriptor less than this value, in order to avoid
** opening database file using file descriptors that are commonly used for
** standard input, output, and error.
 */

// C documentation
//
//	/*
//	** Read data from a file into a buffer.  Return SQLITE_OK if all
//	** bytes were read successfully and SQLITE_IOERR if anything goes
//	** wrong.
//	*/
func _unixRead(tls *libc.TLS, id uintptr, pBuf uintptr, amt int32, offset Tsqlite3_int64) (r int32) {
	var got, nCopy int32
	var pFile uintptr
	_, _, _ = got, nCopy, pFile
	pFile = id
	/* If this is a database file (not a journal, super-journal or temp
	 ** file), the bytes in the locking range should never be read or written. */
	/* Deal with as much of this read request as possible by transferring
	 ** data from the memory mapping using memcpy().  */
	if offset < (*TunixFile)(unsafe.Pointer(pFile)).FmmapSize {
		if offset+int64(amt) <= (*TunixFile)(unsafe.Pointer(pFile)).FmmapSize {
			libc.Xmemcpy(tls, pBuf, (*TunixFile)(unsafe.Pointer(pFile)).FpMapRegion+uintptr(offset), libc.Uint32FromInt32(amt))
			return SQLITE_OK
		} else {
			nCopy = int32((*TunixFile)(unsafe.Pointer(pFile)).FmmapSize - offset)
			libc.Xmemcpy(tls, pBuf, (*TunixFile)(unsafe.Pointer(pFile)).FpMapRegion+uintptr(offset), libc.Uint32FromInt32(nCopy))
			pBuf = pBuf + uintptr(nCopy)
			amt = amt - nCopy
			offset = offset + int64(nCopy)
		}
	}
	got = _seekAndRead(tls, pFile, offset, pBuf, amt)
	if got == amt {
		return SQLITE_OK
	} else {
		if got < 0 {
			/* pFile->lastErrno has been set by seekAndRead().
			 ** Usually we return SQLITE_IOERR_READ here, though for some
			 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS.  The
			 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
			 ** prior to returning to the application by the sqlite3ApiExit()
			 ** routine.
			 */
			switch (*TunixFile)(unsafe.Pointer(pFile)).FlastErrno {
			case int32(ERANGE):
				fallthrough
			case int32(EIO):
				fallthrough
			case int32(ENXIO):
				return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(33)<<libc.Int32FromInt32(8)
			}
			return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
		} else {
			_storeLastErrno(tls, pFile, 0) /* not a system error */
			/* Unread parts of the buffer must be zero-filled */
			libc.Xmemset(tls, pBuf+uintptr(got), 0, libc.Uint32FromInt32(amt-got))
			return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(2)<<libc.Int32FromInt32(8)
		}
	}
	return r
}

// C documentation
//
//	/*
//	** This is the xSetSystemCall() method of sqlite3_vfs for all of the
//	** "unix" VFSes.  Return SQLITE_OK upon successfully updating the
//	** system call pointer, or SQLITE_NOTFOUND if there is no configurable
//	** system call named zName.
//	*/
func _unixSetSystemCall(tls *libc.TLS, pNotUsed uintptr, zName uintptr, __ccgo_fp_pNewFunc Tsqlite3_syscall_ptr) (r int32) {
	var i uint32
	var rc int32
	_, _ = i, rc
	rc = int32(SQLITE_NOTFOUND)
	_ = pNotUsed
	if zName == uintptr(0) {
		/* If no zName is given, restore all system calls to their default
		 ** settings and return NULL
		 */
		rc = SQLITE_OK
		i = uint32(0)
		for {
			if !(i < libc.Uint32FromInt64(348)/libc.Uint32FromInt64(12)) {
				break
			}
			if _aSyscall[i].FpDefault != 0 {
				_aSyscall[i].FpCurrent = _aSyscall[i].FpDefault
			}
			goto _1
		_1:
			;
			i = i + 1
		}
	} else {
		/* If zName is specified, operate on only the one system call
		 ** specified.
		 */
		i = uint32(0)
		for {
			if !(i < libc.Uint32FromInt64(348)/libc.Uint32FromInt64(12)) {
				break
			}
			if libc.Xstrcmp(tls, zName, _aSyscall[i].FzName) == 0 {
				if _aSyscall[i].FpDefault == uintptr(0) {
					_aSyscall[i].FpDefault = _aSyscall[i].FpCurrent
				}
				rc = SQLITE_OK
				if __ccgo_fp_pNewFunc == uintptr(0) {
					__ccgo_fp_pNewFunc = _aSyscall[i].FpDefault
				}
				_aSyscall[i].FpCurrent = __ccgo_fp_pNewFunc
				break
			}
			goto _2
		_2:
			;
			i = i + 1
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
//	**
//	** This is not a VFS shared-memory method; it is a utility function called
//	** by VFS shared-memory methods.
//	*/
func _unixShmPurge(tls *libc.TLS, pFd uintptr) {
	var i, nShmPerMap int32
	var p uintptr
	_, _, _ = i, nShmPerMap, p
	p = (*TunixInodeInfo)(unsafe.Pointer((*TunixFile)(unsafe.Pointer(pFd)).FpInode)).FpShmNode
	if p != 0 && (*TunixShmNode)(unsafe.Pointer(p)).FnRef == 0 {
		nShmPerMap = _unixShmRegionPerMap(tls)
		Xsqlite3_mutex_free(tls, (*TunixShmNode)(unsafe.Pointer(p)).FpShmMutex)
		i = 0
		for {
			if !(i < libc.Int32FromUint16((*TunixShmNode)(unsafe.Pointer(p)).FnRegion)) {
				break
			}
			if (*TunixShmNode)(unsafe.Pointer(p)).FhShm >= 0 {
				(*(*func(*libc.TLS, uintptr, Tsize_t) int32)(unsafe.Pointer(&struct{ uintptr }{_aSyscall[int32(23)].FpCurrent})))(tls, **(**uintptr)(__ccgo_up((*TunixShmNode)(unsafe.Pointer(p)).FapRegion + uintptr(i)*4)), libc.Uint32FromInt32((*TunixShmNode)(unsafe.Pointer(p)).FszRegion))
			} else {
				Xsqlite3_free(tls, **(**uintptr)(__ccgo_up((*TunixShmNode)(unsafe.Pointer(p)).FapRegion + uintptr(i)*4)))
			}
			goto _1
		_1:
			;
			i = i + nShmPerMap
		}
		Xsqlite3_free(tls, (*TunixShmNode)(unsafe.Pointer(p)).FapRegion)
		if (*TunixShmNode)(unsafe.Pointer(p)).FhShm >= 0 {
			_robust_close(tls, pFd, (*TunixShmNode)(unsafe.Pointer(p)).FhShm, int32(45030))
			(*TunixShmNode)(unsafe.Pointer(p)).FhShm = -int32(1)
		}
		(*TunixInodeInfo)(unsafe.Pointer((*TunixShmNode)(unsafe.Pointer(p)).FpInode)).FpShmNode = uintptr(0)
		Xsqlite3_free(tls, p)
	}
}

// C documentation
//
//	/*
//	** Close a connection to shared-memory.  Delete the underlying
//	** storage if deleteFlag is true.
//	**
//	** If there is no shared memory associated with the connection then this
//	** routine is a harmless no-op.
//	*/
func _unixShmUnmap(tls *libc.TLS, fd uintptr, deleteFlag int32) (r int32) {
	var p, pDbFd, pShmNode, pp uintptr
	_, _, _, _ = p, pDbFd, pShmNode, pp /* The underlying database file */
	pDbFd = fd
	p = (*TunixFile)(unsafe.Pointer(pDbFd)).FpShm
	if p == uintptr(0) {
		return SQLITE_OK
	}
	pShmNode = (*TunixShm)(unsafe.Pointer(p)).FpShmNode
	/* Remove connection p from the set of connections associated
	 ** with pShmNode */
	Xsqlite3_mutex_enter(tls, (*TunixShmNode)(unsafe.Pointer(pShmNode)).FpShmMutex)
	pp = pShmNode + 32
	for {
		if !(**(**uintptr)(__ccgo_up(pp)) != p) {
			break
		}
		goto _1
	_1:
		;
		pp = **(**uintptr)(__ccgo_up(pp)) + 4
	}
	**(**uintptr)(__ccgo_up(pp)) = (*TunixShm)(unsafe.Pointer(p)).FpNext
	/* Free the connection p */
	Xsqlite3_free(tls, p)
	(*TunixFile)(unsafe.Pointer(pDbFd)).FpShm = uintptr(0)
	Xsqlite3_mutex_leave(tls, (*TunixShmNode)(unsafe.Pointer(pShmNode)).FpShmMutex)
	/* If pShmNode->nRef has reached 0, then close the underlying
	 ** shared-memory file, too */
	_unixEnterMutex(tls)
	(*TunixShmNode)(unsafe.Pointer(pShmNode)).FnRef = (*TunixShmNode)(unsafe.Pointer(pShmNode)).FnRef - 1
	if (*TunixShmNode)(unsafe.Pointer(pShmNode)).FnRef == 0 {
		if deleteFlag != 0 && (*TunixShmNode)(unsafe.Pointer(pShmNode)).FhShm >= 0 {
			(*(*func(*libc.TLS, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{_aSyscall[int32(16)].FpCurrent})))(tls, (*TunixShmNode)(unsafe.Pointer(pShmNode)).FzFilename)
		}
		_unixShmPurge(tls, pDbFd)
	}
	_unixLeaveMutex(tls)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** If it is currently memory mapped, unmap file pFd.
//	*/
func _unixUnmapfile(tls *libc.TLS, pFd uintptr) {
	if (*TunixFile)(unsafe.Pointer(pFd)).FpMapRegion != 0 {
		(*(*func(*libc.TLS, uintptr, Tsize_t) int32)(unsafe.Pointer(&struct{ uintptr }{_aSyscall[int32(23)].FpCurrent})))(tls, (*TunixFile)(unsafe.Pointer(pFd)).FpMapRegion, libc.Uint32FromInt64((*TunixFile)(unsafe.Pointer(pFd)).FmmapSizeActual))
		(*TunixFile)(unsafe.Pointer(pFd)).FpMapRegion = uintptr(0)
		(*TunixFile)(unsafe.Pointer(pFd)).FmmapSize = 0
		(*TunixFile)(unsafe.Pointer(pFd)).FmmapSizeActual = 0
	}
}

// C documentation
//
//	/* Undo the work of sqlite3SetJoinExpr().  This is used when a LEFT JOIN
//	** is simplified into an ordinary JOIN, and when an ON expression is
//	** "pushed down" into the WHERE clause of a subquery.
//	**
//	** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
//	** an ordinary term that omits the EP_OuterON mark.  Or if iTable<0, then
//	** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
//	**
//	** If nullable is true, that means that Expr p might evaluate to NULL even
//	** if it is a reference to a NOT NULL column.  This can happen, for example,
//	** if the table that p references is on the left side of a RIGHT JOIN.
//	** If nullable is true, then take care to not remove the EP_CanBeNull bit.
//	** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
//	*/
func _unsetJoinExpr(tls *libc.TLS, p uintptr, iTable int32, nullable int32) {
	var i int32
	_ = i
	for p != 0 {
		if iTable < 0 || (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0) && *(*int32)(unsafe.Pointer(p + 36)) == iTable {
			**(**Tu32)(__ccgo_up(p + 4)) &= ^libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON) | libc.Int32FromInt32(EP_InnerON))
			if iTable >= 0 {
				**(**Tu32)(__ccgo_up(p + 4)) |= libc.Uint32FromInt32(libc.Int32FromInt32(EP_InnerON))
			}
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_COLUMN) && (*TExpr)(unsafe.Pointer(p)).FiTable == iTable && !(nullable != 0) {
			**(**Tu32)(__ccgo_up(p + 4)) &= ^libc.Uint32FromInt32(libc.Int32FromInt32(EP_CanBeNull))
		}
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(p)).Fop) == int32(TK_FUNCTION) {
			if *(*uintptr)(unsafe.Pointer(p + 20)) != 0 {
				i = 0
				for {
					if !(i < (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(p + 20)))).FnExpr) {
						break
					}
					_unsetJoinExpr(tls, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(p + 20)) + 8 + uintptr(i)*20))).FpExpr, iTable, nullable)
					goto _1
				_1:
					;
					i = i + 1
				}
			}
		}
		_unsetJoinExpr(tls, (*TExpr)(unsafe.Pointer(p)).FpLeft, iTable, nullable)
		p = (*TExpr)(unsafe.Pointer(p)).FpRight
	}
}

// C documentation
//
//	/*
//	** Generate code that will update the accumulator memory cells for an
//	** aggregate based on the current cursor position.
//	**
//	** If regAcc is non-zero and there are no min() or max() aggregates
//	** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
//	** registers if register regAcc contains 0. The caller will take care
//	** of setting and clearing regAcc.
//	**
//	** For an ORDER BY aggregate, the actual accumulator memory cell update
//	** is deferred until after all input rows have been received, so that they
//	** can be run in the requested order.  In that case, instead of invoking
//	** OP_AggStep to update the accumulator, just add the arguments that would
//	** have been passed into OP_AggStep into the sorting ephemeral table
//	** (along with the appropriate sort key).
//	*/
func _updateAccumulator(tls *libc.TLS, pParse uintptr, regAcc int32, pAggInfo uintptr, eDistinctType int32) {
	var addrHitTest, addrNext, i, j, jj, kk, nArg, regAgg, regAggSz, regBase, regDistinct, regHit, v2 int32
	var pC, pColl, pF, pFilter, pItem, pList, pOBList, v, v3 uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addrHitTest, addrNext, i, j, jj, kk, nArg, pC, pColl, pF, pFilter, pItem, pList, pOBList, regAgg, regAggSz, regBase, regDistinct, regHit, v, v2, v3
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe
	regHit = 0
	addrHitTest = 0
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		return
	}
	(*TAggInfo)(unsafe.Pointer(pAggInfo)).FdirectMode = uint8(1)
	i = 0
	pF = (*TAggInfo)(unsafe.Pointer(pAggInfo)).FaFunc
	for {
		if !(i < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnFunc) {
			break
		}
		addrNext = 0
		regAggSz = 0
		regDistinct = 0
		pList = *(*uintptr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr + 20))
		if (*TExpr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_WinFunc)) != uint32(0) {
			pFilter = (*TWindow)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TExpr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr)).Fy)))).FpFilter
			if (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnAccumulator != 0 && (*TFuncDef)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFunc)).FfuncFlags&uint32(SQLITE_FUNC_NEEDCOLL) != 0 && regAcc != 0 {
				/* If regAcc==0, there there exists some min() or max() function
				 ** without a FILTER clause that will ensure the magnet registers
				 ** are populated. */
				if regHit == 0 {
					v3 = pParse + 48
					*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
					v2 = *(*int32)(unsafe.Pointer(v3))
					regHit = v2
				}
				/* If this is the first row of the group (regAcc contains 0), clear the
				 ** "magnet" register regHit so that the accumulator registers
				 ** are populated if the FILTER clause jumps over the the
				 ** invocation of min() or max() altogether. Or, if this is not
				 ** the first row (regAcc contains 1), set the magnet register so that
				 ** the accumulators are not populated unless the min()/max() is invoked
				 ** and indicates that they should be.  */
				_sqlite3VdbeAddOp2(tls, v, int32(OP_Copy), regAcc, regHit)
			}
			addrNext = _sqlite3VdbeMakeLabel(tls, pParse)
			_sqlite3ExprIfFalse(tls, pParse, pFilter, addrNext, int32(SQLITE_JUMPIFNULL))
		}
		if (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab >= 0 { /* The ORDER BY clause */
			nArg = (*TExprList)(unsafe.Pointer(pList)).FnExpr
			pOBList = *(*uintptr)(unsafe.Pointer((*TExpr)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFExpr)).FpLeft + 20))
			regAggSz = (*TExprList)(unsafe.Pointer(pOBList)).FnExpr
			if !((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBUnique != 0) {
				regAggSz = regAggSz + 1 /* One register for OP_Sequence */
			}
			if (*TAggInfo_func)(unsafe.Pointer(pF)).FbOBPayload != 0 {
				regAggSz = regAggSz + nArg
			}
			if (*TAggInfo_func)(unsafe.Pointer(pF)).FbUseSubtype != 0 {
				regAggSz = regAggSz + nArg
			}
			regAggSz = regAggSz + 1 /* One extra register to hold result of MakeRecord */
			regAgg = _sqlite3GetTempRange(tls, pParse, regAggSz)
			regDistinct = regAgg
			_sqlite3ExprCodeExprList(tls, pParse, pOBList, regAgg, 0, uint8(SQLITE_ECEL_DUP))
			jj = (*TExprList)(unsafe.Pointer(pOBList)).FnExpr
			if !((*TAggInfo_func)(unsafe.Pointer(pF)).FbOBUnique != 0) {
				_sqlite3VdbeAddOp2(tls, v, int32(OP_Sequence), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab, regAgg+jj)
				jj = jj + 1
			}
			if (*TAggInfo_func)(unsafe.Pointer(pF)).FbOBPayload != 0 {
				regDistinct = regAgg + jj
				_sqlite3ExprCodeExprList(tls, pParse, pList, regDistinct, 0, uint8(SQLITE_ECEL_DUP))
				jj = jj + nArg
			}
			if (*TAggInfo_func)(unsafe.Pointer(pF)).FbUseSubtype != 0 {
				if (*TAggInfo_func)(unsafe.Pointer(pF)).FbOBPayload != 0 {
					v2 = regDistinct
				} else {
					v2 = regAgg
				}
				regBase = v2
				kk = 0
				for {
					if !(kk < nArg) {
						break
					}
					_sqlite3VdbeAddOp2(tls, v, int32(OP_GetSubtype), regBase+kk, regAgg+jj)
					goto _5
				_5:
					;
					kk = kk + 1
					jj = jj + 1
				}
			}
		} else {
			if pList != 0 {
				nArg = (*TExprList)(unsafe.Pointer(pList)).FnExpr
				regAgg = _sqlite3GetTempRange(tls, pParse, nArg)
				regDistinct = regAgg
				_sqlite3ExprCodeExprList(tls, pParse, pList, regAgg, 0, uint8(SQLITE_ECEL_DUP))
			} else {
				nArg = 0
				regAgg = 0
			}
		}
		if (*TAggInfo_func)(unsafe.Pointer(pF)).FiDistinct >= 0 && pList != 0 {
			if addrNext == 0 {
				addrNext = _sqlite3VdbeMakeLabel(tls, pParse)
			}
			(*TAggInfo_func)(unsafe.Pointer(pF)).FiDistinct = _codeDistinct(tls, pParse, eDistinctType, (*TAggInfo_func)(unsafe.Pointer(pF)).FiDistinct, addrNext, pList, regDistinct)
		}
		if (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab >= 0 {
			/* Insert a new record into the ORDER BY table */
			_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), regAgg, regAggSz-int32(1), regAgg+regAggSz-int32(1))
			_sqlite3VdbeAddOp4Int(tls, v, int32(OP_IdxInsert), (*TAggInfo_func)(unsafe.Pointer(pF)).FiOBTab, regAgg+regAggSz-int32(1), regAgg, regAggSz-int32(1))
			_sqlite3ReleaseTempRange(tls, pParse, regAgg, regAggSz)
		} else {
			/* Invoke the AggStep function */
			if (*TFuncDef)(unsafe.Pointer((*TAggInfo_func)(unsafe.Pointer(pF)).FpFunc)).FfuncFlags&uint32(SQLITE_FUNC_NEEDCOLL) != 0 {
				pColl = uintptr(0)
				/* pList!=0 if pF->pFunc has NEEDCOLL */
				j = 0
				pItem = pList + 8
				for {
					if !(!(pColl != 0) && j < nArg) {
						break
					}
					pColl = _sqlite3ExprCollSeq(tls, pParse, (*TExprList_item)(unsafe.Pointer(pItem)).FpExpr)
					goto _6
				_6:
					;
					j = j + 1
					pItem += 20
				}
				if !(pColl != 0) {
					pColl = (*Tsqlite3)(unsafe.Pointer((*TParse)(unsafe.Pointer(pParse)).Fdb)).FpDfltColl
				}
				if regHit == 0 && (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnAccumulator != 0 {
					v3 = pParse + 48
					*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
					v2 = *(*int32)(unsafe.Pointer(v3))
					regHit = v2
				}
				_sqlite3VdbeAddOp4(tls, v, int32(OP_CollSeq), regHit, 0, 0, pColl, -int32(2))
			}
			_sqlite3VdbeAddOp3(tls, v, int32(OP_AggStep), 0, regAgg, (*TAggInfo)(unsafe.Pointer(pAggInfo)).FiFirstReg+(*TAggInfo)(unsafe.Pointer(pAggInfo)).FnColumn+i)
			_sqlite3VdbeAppendP4(tls, v, (*TAggInfo_func)(unsafe.Pointer(pF)).FpFunc, -int32(8))
			_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(nArg))
			_sqlite3ReleaseTempRange(tls, pParse, regAgg, nArg)
		}
		if addrNext != 0 {
			_sqlite3VdbeResolveLabel(tls, v, addrNext)
		}
		if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
			return
		}
		goto _1
	_1:
		;
		i = i + 1
		pF += 24
	}
	if regHit == 0 && (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnAccumulator != 0 {
		regHit = regAcc
	}
	if regHit != 0 {
		addrHitTest = _sqlite3VdbeAddOp1(tls, v, int32(OP_If), regHit)
	}
	i = 0
	pC = (*TAggInfo)(unsafe.Pointer(pAggInfo)).FaCol
	for {
		if !(i < (*TAggInfo)(unsafe.Pointer(pAggInfo)).FnAccumulator) {
			break
		}
		_sqlite3ExprCode(tls, pParse, (*TAggInfo_col)(unsafe.Pointer(pC)).FpCExpr, (*TAggInfo)(unsafe.Pointer(pAggInfo)).FiFirstReg+i)
		if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
			return
		}
		goto _9
	_9:
		;
		i = i + 1
		pC += 20
	}
	(*TAggInfo)(unsafe.Pointer(pAggInfo)).FdirectMode = uint8(0)
	if addrHitTest != 0 {
		_sqlite3VdbeJumpHereOrPopInst(tls, v, addrHitTest)
	}
}

// C documentation
//
//	/*
//	** Assuming both the pLimit and pOrderBy parameters are NULL, this function
//	** generates VM code to run the query:
//	**
//	**   SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
//	**
//	** and write the results to the ephemeral table already opened as cursor
//	** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
//	** this function, they must be deleted by the caller.
//	**
//	** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
//	**
//	**   SELECT <other-columns>, pChanges FROM pTabList
//	**   WHERE pWhere
//	**   GROUP BY <other-columns>
//	**   ORDER BY pOrderBy LIMIT pLimit
//	**
//	** If pTab is a view, the GROUP BY clause is omitted.
//	**
//	** Exactly how results are written to table iEph, and exactly what
//	** the <other-columns> in the query above are is determined by the type
//	** of table pTabList->a[0].pTab.
//	**
//	** If the table is a WITHOUT ROWID table, then argument pPk must be its
//	** PRIMARY KEY. In this case <other-columns> are the primary key columns
//	** of the table, in order. The results of the query are written to ephemeral
//	** table iEph as index keys, using OP_IdxInsert.
//	**
//	** If the table is actually a view, then <other-columns> are all columns of
//	** the view. The results are written to the ephemeral table iEph as records
//	** with automatically assigned integer keys.
//	**
//	** If the table is a virtual or ordinary intkey table, then <other-columns>
//	** is its rowid. For a virtual table, the results are written to iEph as
//	** records with automatically assigned integer keys For intkey tables, the
//	** rowid value in <other-columns> is used as the integer key, and the
//	** remaining fields make up the table record.
//	*/
func _updateFromSelect(tls *libc.TLS, pParse uintptr, iEph int32, pPk uintptr, pChanges uintptr, pTabList uintptr, pWhere uintptr, pOrderBy uintptr, pLimit uintptr) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var db, pGrp, pLimit2, pList, pNew, pOrderBy2, pSelect, pSrc, pTab, pWhere2 uintptr
	var eDest, i, v2 int32
	var _ /* dest at bp+0 */ TSelectDest
	_, _, _, _, _, _, _, _, _, _, _, _, _ = db, eDest, i, pGrp, pLimit2, pList, pNew, pOrderBy2, pSelect, pSrc, pTab, pWhere2, v2
	pSelect = uintptr(0)
	pList = uintptr(0)
	pGrp = uintptr(0)
	pLimit2 = uintptr(0)
	pOrderBy2 = uintptr(0)
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	pTab = (*(*TSrcItem)(unsafe.Pointer(pTabList + 8))).FpSTab
	_ = pOrderBy
	_ = pLimit
	pSrc = _sqlite3SrcListDup(tls, db, pTabList, 0)
	pWhere2 = _sqlite3ExprDup(tls, db, pWhere, 0)
	if pSrc != 0 {
		(*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FiCursor = -int32(1)
		(*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FpSTab)).FnTabRef = (*TTable)(unsafe.Pointer((*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FpSTab)).FnTabRef - 1
		(*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FpSTab = uintptr(0)
	}
	if pPk != 0 {
		i = 0
		for {
			if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pPk)).FnKeyCol)) {
				break
			}
			pNew = _exprRowColumn(tls, pParse, int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pPk)).FaiColumn + uintptr(i)*2))))
			pList = _sqlite3ExprListAppend(tls, pParse, pList, pNew)
			goto _1
		_1:
			;
			i = i + 1
		}
		if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VTAB) {
			v2 = int32(SRT_Table)
		} else {
			v2 = int32(SRT_Upfrom)
		}
		eDest = v2
	} else {
		if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VIEW) {
			i = 0
			for {
				if !(i < int32((*TTable)(unsafe.Pointer(pTab)).FnCol)) {
					break
				}
				pList = _sqlite3ExprListAppend(tls, pParse, pList, _exprRowColumn(tls, pParse, i))
				goto _3
			_3:
				;
				i = i + 1
			}
			eDest = int32(SRT_Table)
		} else {
			if libc.Int32FromUint8((*TTable)(unsafe.Pointer(pTab)).FeTabType) == int32(TABTYP_VTAB) {
				v2 = int32(SRT_Table)
			} else {
				v2 = int32(SRT_Upfrom)
			}
			eDest = v2
			pList = _sqlite3ExprListAppend(tls, pParse, uintptr(0), _sqlite3PExpr(tls, pParse, int32(TK_ROW), uintptr(0), uintptr(0)))
		}
	}
	if pChanges != 0 {
		i = 0
		for {
			if !(i < (*TExprList)(unsafe.Pointer(pChanges)).FnExpr) {
				break
			}
			pList = _sqlite3ExprListAppend(tls, pParse, pList, _sqlite3ExprDup(tls, db, (*(*TExprList_item)(unsafe.Pointer(pChanges + 8 + uintptr(i)*20))).FpExpr, 0))
			goto _5
		_5:
			;
			i = i + 1
		}
	}
	pSelect = _sqlite3SelectNew(tls, pParse, pList, pSrc, pWhere2, pGrp, uintptr(0), pOrderBy2, libc.Uint32FromInt32(libc.Int32FromInt32(SF_UFSrcCheck)|libc.Int32FromInt32(SF_IncludeHidden)|libc.Int32FromInt32(SF_UpdateFrom)), pLimit2)
	if pSelect != 0 {
		**(**Tu32)(__ccgo_up(pSelect + 4)) |= uint32(SF_OrderByReqd)
	}
	_sqlite3SelectDestInit(tls, bp, eDest, iEph)
	if pPk != 0 {
		v2 = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pPk)).FnKeyCol)
	} else {
		v2 = -int32(1)
	}
	(**(**TSelectDest)(__ccgo_up(bp))).FiSDParm2 = v2
	_sqlite3Select(tls, pParse, pSelect, bp)
	_sqlite3SelectDelete(tls, db, pSelect)
}

// C documentation
//
//	/*
//	** Generate code for an UPDATE of a virtual table.
//	**
//	** There are two possible strategies - the default and the special
//	** "onepass" strategy. Onepass is only used if the virtual table
//	** implementation indicates that pWhere may match at most one row.
//	**
//	** The default strategy is to create an ephemeral table that contains
//	** for each row to be changed:
//	**
//	**   (A)  The original rowid of that row.
//	**   (B)  The revised rowid for the row.
//	**   (C)  The content of every column in the row.
//	**
//	** Then loop through the contents of this ephemeral table executing a
//	** VUpdate for each row. When finished, drop the ephemeral table.
//	**
//	** The "onepass" strategy does not use an ephemeral table. Instead, it
//	** stores the same values (A, B and C above) in a register array and
//	** makes a single invocation of VUpdate.
//	*/
func _updateVirtualTable(tls *libc.TLS, pParse uintptr, pSrc uintptr, pTab uintptr, pChanges uintptr, pRowid uintptr, aXRef uintptr, pWhere uintptr, onError int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var addr, eOnePass, ephemTab, i, iCsr, nArg, regArg, regRec, regRowid, v1 int32
	var db, pList, pPk, pPk1, pRow, pRowExpr, pVTab, pWInfo, v, v2 uintptr
	var iPk, iPk1 Ti16
	var _ /* aDummy at bp+0 */ [2]int32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addr, db, eOnePass, ephemTab, i, iCsr, iPk, iPk1, nArg, pList, pPk, pPk1, pRow, pRowExpr, pVTab, pWInfo, regArg, regRec, regRowid, v, v1, v2
	v = (*TParse)(unsafe.Pointer(pParse)).FpVdbe /* Loop counter */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb   /* Database connection */
	pVTab = _sqlite3GetVTable(tls, db, pTab)
	pWInfo = uintptr(0)
	nArg = int32(2) + int32((*TTable)(unsafe.Pointer(pTab)).FnCol) /* Register for ephemeral table rowid */
	iCsr = (*(*TSrcItem)(unsafe.Pointer(pSrc + 8))).FiCursor       /* Address of OP_OpenEphemeral */
	/* Allocate nArg registers in which to gather the arguments for VUpdate. Then
	 ** create and open the ephemeral table in which the records created from
	 ** these arguments will be temporarily stored. */
	v2 = pParse + 44
	v1 = *(*int32)(unsafe.Pointer(v2))
	*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
	ephemTab = v1
	addr = _sqlite3VdbeAddOp2(tls, v, int32(OP_OpenEphemeral), ephemTab, nArg)
	regArg = (*TParse)(unsafe.Pointer(pParse)).FnMem + int32(1)
	**(**int32)(__ccgo_up(pParse + 48)) += nArg
	if (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc > int32(1) {
		pPk = uintptr(0)
		if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_WithoutRowid) == uint32(0) {
			if pRowid != 0 {
				pRow = _sqlite3ExprDup(tls, db, pRowid, 0)
			} else {
				pRow = _sqlite3PExpr(tls, pParse, int32(TK_ROW), uintptr(0), uintptr(0))
			}
		} else { /* PRIMARY KEY column */
			pPk = _sqlite3PrimaryKeyIndex(tls, pTab)
			iPk = **(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pPk)).FaiColumn))
			if **(**int32)(__ccgo_up(aXRef + uintptr(iPk)*4)) >= 0 {
				pRow = _sqlite3ExprDup(tls, db, (*(*TExprList_item)(unsafe.Pointer(pChanges + 8 + uintptr(**(**int32)(__ccgo_up(aXRef + uintptr(iPk)*4)))*20))).FpExpr, 0)
			} else {
				pRow = _exprRowColumn(tls, pParse, int32(iPk))
			}
		}
		pList = _sqlite3ExprListAppend(tls, pParse, uintptr(0), pRow)
		i = 0
		for {
			if !(i < int32((*TTable)(unsafe.Pointer(pTab)).FnCol)) {
				break
			}
			if **(**int32)(__ccgo_up(aXRef + uintptr(i)*4)) >= 0 {
				pList = _sqlite3ExprListAppend(tls, pParse, pList, _sqlite3ExprDup(tls, db, (*(*TExprList_item)(unsafe.Pointer(pChanges + 8 + uintptr(**(**int32)(__ccgo_up(aXRef + uintptr(i)*4)))*20))).FpExpr, 0))
			} else {
				pRowExpr = _exprRowColumn(tls, pParse, i)
				if pRowExpr != 0 {
					(*TExpr)(unsafe.Pointer(pRowExpr)).Fop2 = uint8(OPFLAG_NOCHNG)
				}
				pList = _sqlite3ExprListAppend(tls, pParse, pList, pRowExpr)
			}
			goto _3
		_3:
			;
			i = i + 1
		}
		_updateFromSelect(tls, pParse, ephemTab, pPk, pList, pSrc, pWhere, uintptr(0), uintptr(0))
		_sqlite3ExprListDelete(tls, db, pList)
		eOnePass = ONEPASS_OFF
	} else {
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		regRec = v1
		v2 = pParse + 48
		*(*int32)(unsafe.Pointer(v2)) = *(*int32)(unsafe.Pointer(v2)) + 1
		v1 = *(*int32)(unsafe.Pointer(v2))
		regRowid = v1
		/* Start scanning the virtual table */
		pWInfo = _sqlite3WhereBegin(tls, pParse, pSrc, pWhere, uintptr(0), uintptr(0), uintptr(0), uint16(WHERE_ONEPASS_DESIRED), 0)
		if pWInfo == uintptr(0) {
			return
		}
		/* Populate the argument registers. */
		i = 0
		for {
			if !(i < int32((*TTable)(unsafe.Pointer(pTab)).FnCol)) {
				break
			}
			if **(**int32)(__ccgo_up(aXRef + uintptr(i)*4)) >= 0 {
				_sqlite3ExprCode(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(pChanges + 8 + uintptr(**(**int32)(__ccgo_up(aXRef + uintptr(i)*4)))*20))).FpExpr, regArg+int32(2)+i)
			} else {
				_sqlite3VdbeAddOp3(tls, v, int32(OP_VColumn), iCsr, i, regArg+int32(2)+i)
				_sqlite3VdbeChangeP5(tls, v, uint16(OPFLAG_NOCHNG)) /* For sqlite3_vtab_nochange() */
			}
			goto _8
		_8:
			;
			i = i + 1
		}
		if (*TTable)(unsafe.Pointer(pTab)).FtabFlags&uint32(TF_WithoutRowid) == uint32(0) {
			_sqlite3VdbeAddOp2(tls, v, int32(OP_Rowid), iCsr, regArg)
			if pRowid != 0 {
				_sqlite3ExprCode(tls, pParse, pRowid, regArg+int32(1))
			} else {
				_sqlite3VdbeAddOp2(tls, v, int32(OP_Rowid), iCsr, regArg+int32(1))
			}
		} else { /* PRIMARY KEY column */
			pPk1 = _sqlite3PrimaryKeyIndex(tls, pTab)
			iPk1 = **(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pPk1)).FaiColumn))
			_sqlite3VdbeAddOp3(tls, v, int32(OP_VColumn), iCsr, int32(iPk1), regArg)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_SCopy), regArg+int32(2)+int32(iPk1), regArg+int32(1))
		}
		eOnePass = _sqlite3WhereOkOnePass(tls, pWInfo, bp)
		/* There is no ONEPASS_MULTI on virtual tables */
		if eOnePass != 0 {
			/* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
			 ** above. */
			_sqlite3VdbeChangeToNoop(tls, v, addr)
			_sqlite3VdbeAddOp1(tls, v, int32(OP_Close), iCsr)
		} else {
			/* Create a record from the argument register contents and insert it into
			 ** the ephemeral table. */
			_sqlite3MultiWrite(tls, pParse)
			_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), regArg, nArg, regRec)
			_sqlite3VdbeAddOp2(tls, v, int32(OP_NewRowid), ephemTab, regRowid)
			_sqlite3VdbeAddOp3(tls, v, int32(OP_Insert), ephemTab, regRec, regRowid)
		}
	}
	if eOnePass == ONEPASS_OFF {
		/* End the virtual table scan */
		if (*TSrcList)(unsafe.Pointer(pSrc)).FnSrc == int32(1) {
			_sqlite3WhereEnd(tls, pWInfo)
		}
		/* Begin scanning through the ephemeral table. */
		addr = _sqlite3VdbeAddOp1(tls, v, int32(OP_Rewind), ephemTab)
		/* Extract arguments from the current row of the ephemeral table and
		 ** invoke the VUpdate method.  */
		i = 0
		for {
			if !(i < nArg) {
				break
			}
			_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), ephemTab, i, regArg+i)
			goto _9
		_9:
			;
			i = i + 1
		}
	}
	_sqlite3VtabMakeWritable(tls, pParse, pTab)
	_sqlite3VdbeAddOp4(tls, v, int32(OP_VUpdate), 0, nArg, regArg, pVTab, -int32(12))
	if onError == int32(OE_Default) {
		v1 = int32(OE_Abort)
	} else {
		v1 = onError
	}
	_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(v1))
	_sqlite3MayAbort(tls, pParse)
	/* End of the ephemeral table scan. Or, if using the onepass strategy,
	 ** jump to here if the scan visited zero rows. */
	if eOnePass == ONEPASS_OFF {
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Next), ephemTab, addr+int32(1))
		_sqlite3VdbeJumpHere(tls, v, addr)
		_sqlite3VdbeAddOp2(tls, v, int32(OP_Close), ephemTab, 0)
	} else {
		_sqlite3WhereEnd(tls, pWInfo)
	}
}

/************** End of update.c **********************************************/
/************** Begin file upsert.c ******************************************/
/*
** 2018-04-12
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement various aspects of UPSERT
** processing and handling of the Upsert object.
 */
/* #include "sqliteInt.h" */

// C documentation
//
//	/*
//	** The pVal argument is known to be a value other than NULL.
//	** Convert it into a string with encoding enc and return a pointer
//	** to a zero-terminated version of that string.
//	*/
func _valueToText(tls *libc.TLS, pVal uintptr, enc Tu8) (r uintptr) {
	var v1 int32
	var v2 uintptr
	_, _ = v1, v2
	if libc.Int32FromUint16((*Tsqlite3_value)(unsafe.Pointer(pVal)).Fflags)&(libc.Int32FromInt32(MEM_Blob)|libc.Int32FromInt32(MEM_Str)) != 0 {
		if libc.Int32FromUint16((*Tsqlite3_value)(unsafe.Pointer(pVal)).Fflags)&int32(MEM_Zero) != 0 {
			v1 = _sqlite3VdbeMemExpandBlob(tls, pVal)
		} else {
			v1 = 0
		}
		if v1 != 0 {
			return uintptr(0)
		}
		v2 = pVal + 16
		*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(MEM_Str))
		if libc.Int32FromUint8((*Tsqlite3_value)(unsafe.Pointer(pVal)).Fenc) != libc.Int32FromUint8(enc) & ^libc.Int32FromInt32(SQLITE_UTF16_ALIGNED) {
			_sqlite3VdbeChangeEncoding(tls, pVal, libc.Int32FromUint8(enc) & ^libc.Int32FromInt32(SQLITE_UTF16_ALIGNED))
		}
		if libc.Int32FromUint8(enc)&int32(SQLITE_UTF16_ALIGNED) != 0 && int32(1) == int32(1)&int32((*Tsqlite3_value)(unsafe.Pointer(pVal)).Fz) {
			if _sqlite3VdbeMemMakeWriteable(tls, pVal) != SQLITE_OK {
				return uintptr(0)
			}
		}
		_sqlite3VdbeMemNulTerminate(tls, pVal) /* IMP: R-31275-44060 */
	} else {
		_sqlite3VdbeMemStringify(tls, pVal, enc, uint8(0))
	}
	if libc.Int32FromUint8((*Tsqlite3_value)(unsafe.Pointer(pVal)).Fenc) == libc.Int32FromUint8(enc) & ^libc.Int32FromInt32(SQLITE_UTF16_ALIGNED) {
		return (*Tsqlite3_value)(unsafe.Pointer(pVal)).Fz
	} else {
		return uintptr(0)
	}
	return r
}

// C documentation
//
//	/*
//	** Change the value of the P4 operand for a specific instruction.
//	** This routine is useful when a large program is loaded from a
//	** static array using sqlite3VdbeAddOpList but we want to make a
//	** few minor changes to the program.
//	**
//	** If n>=0 then the P4 operand is dynamic, meaning that a copy of
//	** the string is made into memory obtained from sqlite3_malloc().
//	** A value of n==0 means copy bytes of zP4 up to and including the
//	** first null byte.  If n>0 then copy n+1 bytes of zP4.
//	**
//	** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
//	** to a string or structure that is guaranteed to exist for the lifetime of
//	** the Vdbe. In these cases we can just copy the pointer.
//	**
//	** If addr<0 then change P4 on the most recently inserted instruction.
//	*/
func _vdbeChangeP4Full(tls *libc.TLS, p uintptr, pOp uintptr, zP4 uintptr, n int32) {
	if (*TOp)(unsafe.Pointer(pOp)).Fp4type != 0 {
		(*TOp)(unsafe.Pointer(pOp)).Fp4type = 0
		*(*uintptr)(unsafe.Pointer(pOp + 16)) = uintptr(0)
	}
	if n < 0 {
		_sqlite3VdbeChangeP4(tls, p, (int32(pOp)-int32((*TVdbe)(unsafe.Pointer(p)).FaOp))/20, zP4, n)
	} else {
		if n == 0 {
			n = _sqlite3Strlen30(tls, zP4)
		}
		*(*uintptr)(unsafe.Pointer(pOp + 16)) = _sqlite3DbStrNDup(tls, (*TVdbe)(unsafe.Pointer(p)).Fdb, zP4, libc.Uint64FromInt32(n))
		(*TOp)(unsafe.Pointer(pOp)).Fp4type = int8(-libc.Int32FromInt32(7))
	}
}

// C documentation
//
//	/*
//	** This function compares the unpacked record with the current key that
//	** cursor pCur points to. If bInt is false, all fields for which the
//	** corresponding bit in parameter "mask" is set are ignored. Or, if
//	** bInt is true, then a difference of BTREE_ULPDISTORTION or fewer ULPs
//	** in real values is overlooked for fields with the corresponding bit
//	** set in mask.
//	**
//	** Return the usual less than zero, zero, or greater than zero if the
//	** remaining fields of the cursor cursor key are less than, equal to or
//	** greater than those in (*p).
//	*/
func _vdbeIsMatchingIndexKey(tls *libc.TLS, pCur uintptr, bInt int32, mask TBitmask, p uintptr, piRes uintptr) (r int32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var aRec uintptr
	var idxHdr, idxRec, nRec Tu32
	var ii, nCol, nSerial, rc, res, v1 int32
	var _ /* iSerial at bp+44 */ Tu32
	var _ /* mem at bp+0 */ TMem
	var _ /* szHdr at bp+40 */ Tu32
	_, _, _, _, _, _, _, _, _, _ = aRec, idxHdr, idxRec, ii, nCol, nRec, nSerial, rc, res, v1
	aRec = uintptr(0)
	nRec = uint32(0)
	rc = SQLITE_OK
	libc.Xmemset(tls, bp, 0, uint32(40))
	(**(**TMem)(__ccgo_up(bp))).Fenc = (*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).Fenc
	(**(**TMem)(__ccgo_up(bp))).Fdb = (*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).Fdb
	nRec = _sqlite3BtreePayloadSize(tls, pCur)
	if nRec > uint32(0x7fffffff) {
		return _sqlite3CorruptError(tls, int32(93336))
	}
	/* Allocate 5 extra bytes at the end of the buffer. This allows the
	 ** getVarint32() call below to read slightly past the end of the buffer
	 ** if the record is corrupt. */
	aRec = _sqlite3MallocZero(tls, uint64(nRec+uint32(5)))
	if aRec == uintptr(0) {
		rc = int32(SQLITE_NOMEM)
	} else {
		rc = _sqlite3BtreePayload(tls, pCur, uint32(0), nRec, aRec)
	}
	if rc == SQLITE_OK {
		**(**Tu32)(__ccgo_up(bp + 40)) = uint32(0) /* Size of record header in bytes */
		idxHdr = uint32(0)                         /* Current index in header */
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aRec))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
			**(**Tu32)(__ccgo_up(bp + 40)) = uint32(**(**Tu8)(__ccgo_up(aRec)))
			v1 = libc.Int32FromInt32(1)
		} else {
			v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aRec, bp+40))
		}
		idxHdr = uint32(libc.Uint8FromInt32(v1))
		if **(**Tu32)(__ccgo_up(bp + 40)) > uint32(98307) {
			rc = int32(SQLITE_CORRUPT)
		} else {
			res = 0                                 /* Result of this function call */
			idxRec = **(**Tu32)(__ccgo_up(bp + 40)) /* Index of next field in record body */
			ii = 0                                  /* Iterator variable */
			nCol = libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo)).FnAllField)
			ii = 0
			for {
				if !(ii < nCol && rc == SQLITE_OK) {
					break
				}
				**(**Tu32)(__ccgo_up(bp + 44)) = uint32(0)
				nSerial = 0
				if idxHdr >= **(**Tu32)(__ccgo_up(bp + 40)) {
					rc = _sqlite3CorruptError(tls, int32(93367))
					break
				}
				if libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aRec + uintptr(idxHdr)))) < libc.Int32FromUint8(libc.Uint8FromInt32(0x80)) {
					**(**Tu32)(__ccgo_up(bp + 44)) = uint32(**(**Tu8)(__ccgo_up(aRec + uintptr(idxHdr))))
					v1 = libc.Int32FromInt32(1)
				} else {
					v1 = libc.Int32FromUint8(_sqlite3GetVarint32(tls, aRec+uintptr(idxHdr), bp+44))
				}
				idxHdr = idxHdr + uint32(libc.Uint8FromInt32(v1))
				nSerial = libc.Int32FromUint32(_sqlite3VdbeSerialTypeLen(tls, **(**Tu32)(__ccgo_up(bp + 44))))
				if idxRec+libc.Uint32FromInt32(nSerial) > nRec {
					rc = _sqlite3CorruptError(tls, int32(93373))
				} else {
					_sqlite3VdbeSerialGet(tls, aRec+uintptr(idxRec), **(**Tu32)(__ccgo_up(bp + 44)), bp)
					if _vdbeSkipField(tls, mask, ii, (*TUnpackedRecord)(unsafe.Pointer(p)).FaMem+uintptr(ii)*40, bp, bInt) == 0 {
						res = _sqlite3MemCompare(tls, bp, (*TUnpackedRecord)(unsafe.Pointer(p)).FaMem+uintptr(ii)*40, *(*uintptr)(unsafe.Pointer((*TUnpackedRecord)(unsafe.Pointer(p)).FpKeyInfo + 20 + uintptr(ii)*4)))
						if res != 0 {
							break
						}
					}
				}
				idxRec = idxRec + _sqlite3VdbeSerialTypeLen(tls, **(**Tu32)(__ccgo_up(bp + 44)))
				goto _2
			_2:
				;
				ii = ii + 1
			}
			**(**int32)(__ccgo_up(piRes)) = res
		}
	}
	Xsqlite3_free(tls, aRec)
	return rc
}

// C documentation
//
//	/*
//	** If the memory cell contains a value that must be freed by
//	** invoking the external callback in Mem.xDel, then this routine
//	** will free that value.  It also sets Mem.flags to MEM_Null.
//	**
//	** This is a helper routine for sqlite3VdbeMemSetNull() and
//	** for sqlite3VdbeMemRelease().  Use those other routines as the
//	** entry point for releasing Mem resources.
//	*/
func _vdbeMemClearExternAndSetNull(tls *libc.TLS, p uintptr) {
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&int32(MEM_Agg) != 0 {
		_sqlite3VdbeMemFinalize(tls, p, *(*uintptr)(unsafe.Pointer(&(*TMem)(unsafe.Pointer(p)).Fu)))
	}
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(p)).Fflags)&int32(MEM_Dyn) != 0 {
		(*(*func(*libc.TLS, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMem)(unsafe.Pointer(p)).FxDel})))(tls, (*TMem)(unsafe.Pointer(p)).Fz)
	}
	(*TMem)(unsafe.Pointer(p)).Fflags = uint16(MEM_Null)
}

// C documentation
//
//	/*
//	** Read the next nByte bytes of data from the PMA p.
//	** If successful, set *ppOut to point to a buffer containing the data
//	** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
//	** error code.
//	**
//	** The buffer returned in *ppOut is only valid until the
//	** next call to this function.
//	*/
func _vdbePmaReadBlob(tls *libc.TLS, p uintptr, nByte int32, ppOut uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aNew uintptr
	var iBuf, nAvail, nCopy, nRead, nRem, rc, rc1 int32
	var nNew Tsqlite3_int64
	var v1 int64
	var _ /* aNext at bp+0 */ uintptr
	_, _, _, _, _, _, _, _, _, _ = aNew, iBuf, nAvail, nCopy, nNew, nRead, nRem, rc, rc1, v1 /* Bytes of data available in buffer */
	if (*TPmaReader)(unsafe.Pointer(p)).FaMap != 0 {
		**(**uintptr)(__ccgo_up(ppOut)) = (*TPmaReader)(unsafe.Pointer(p)).FaMap + uintptr((*TPmaReader)(unsafe.Pointer(p)).FiReadOff)
		**(**Ti64)(__ccgo_up(p)) += int64(nByte)
		return SQLITE_OK
	}
	/* If there is no more data to be read from the buffer, read the next
	 ** p->nBuffer bytes of data from the file into it. Or, if there are less
	 ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
	iBuf = int32((*TPmaReader)(unsafe.Pointer(p)).FiReadOff % int64((*TPmaReader)(unsafe.Pointer(p)).FnBuffer))
	if iBuf == 0 { /* sqlite3OsRead() return code */
		/* Determine how many bytes of data to read. */
		if (*TPmaReader)(unsafe.Pointer(p)).FiEof-(*TPmaReader)(unsafe.Pointer(p)).FiReadOff > int64((*TPmaReader)(unsafe.Pointer(p)).FnBuffer) {
			nRead = (*TPmaReader)(unsafe.Pointer(p)).FnBuffer
		} else {
			nRead = int32((*TPmaReader)(unsafe.Pointer(p)).FiEof - (*TPmaReader)(unsafe.Pointer(p)).FiReadOff)
		}
		/* Readr data from the file. Return early if an error occurs. */
		rc = _sqlite3OsRead(tls, (*TPmaReader)(unsafe.Pointer(p)).FpFd, (*TPmaReader)(unsafe.Pointer(p)).FaBuffer, nRead, (*TPmaReader)(unsafe.Pointer(p)).FiReadOff)
		if rc != SQLITE_OK {
			return rc
		}
	}
	nAvail = (*TPmaReader)(unsafe.Pointer(p)).FnBuffer - iBuf
	if nByte <= nAvail {
		/* The requested data is available in the in-memory buffer. In this
		 ** case there is no need to make a copy of the data, just return a
		 ** pointer into the buffer to the caller.  */
		**(**uintptr)(__ccgo_up(ppOut)) = (*TPmaReader)(unsafe.Pointer(p)).FaBuffer + uintptr(iBuf)
		**(**Ti64)(__ccgo_up(p)) += int64(nByte)
	} else { /* Bytes remaining to copy */
		/* Extend the p->aAlloc[] allocation if required. */
		if (*TPmaReader)(unsafe.Pointer(p)).FnAlloc < nByte {
			if int64(libc.Int32FromInt32(128)) > int64(2)*int64((*TPmaReader)(unsafe.Pointer(p)).FnAlloc) {
				v1 = int64(libc.Int32FromInt32(128))
			} else {
				v1 = int64(2) * int64((*TPmaReader)(unsafe.Pointer(p)).FnAlloc)
			}
			nNew = v1
			for int64(nByte) > nNew {
				nNew = nNew * int64(2)
			}
			aNew = _sqlite3Realloc(tls, (*TPmaReader)(unsafe.Pointer(p)).FaAlloc, libc.Uint64FromInt64(nNew))
			if !(aNew != 0) {
				return int32(SQLITE_NOMEM)
			}
			(*TPmaReader)(unsafe.Pointer(p)).FnAlloc = int32(nNew)
			(*TPmaReader)(unsafe.Pointer(p)).FaAlloc = aNew
		}
		/* Copy as much data as is available in the buffer into the start of
		 ** p->aAlloc[].  */
		libc.Xmemcpy(tls, (*TPmaReader)(unsafe.Pointer(p)).FaAlloc, (*TPmaReader)(unsafe.Pointer(p)).FaBuffer+uintptr(iBuf), libc.Uint32FromInt32(nAvail))
		**(**Ti64)(__ccgo_up(p)) += int64(nAvail)
		nRem = nByte - nAvail
		/* The following loop copies up to p->nBuffer bytes per iteration into
		 ** the p->aAlloc[] buffer.  */
		for nRem > 0 { /* Number of bytes to copy */
			**(**uintptr)(__ccgo_up(bp)) = uintptr(0) /* Pointer to buffer to copy data from */
			nCopy = nRem
			if nRem > (*TPmaReader)(unsafe.Pointer(p)).FnBuffer {
				nCopy = (*TPmaReader)(unsafe.Pointer(p)).FnBuffer
			}
			rc1 = _vdbePmaReadBlob(tls, p, nCopy, bp)
			if rc1 != SQLITE_OK {
				return rc1
			}
			libc.Xmemcpy(tls, (*TPmaReader)(unsafe.Pointer(p)).FaAlloc+uintptr(nByte-nRem), **(**uintptr)(__ccgo_up(bp)), libc.Uint32FromInt32(nCopy))
			nRem = nRem - nCopy
		}
		**(**uintptr)(__ccgo_up(ppOut)) = (*TPmaReader)(unsafe.Pointer(p)).FaAlloc
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Attach PmaReader pReadr to file pFile (if it is not already attached to
//	** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
//	** if successful, or an SQLite error code if an error occurs.
//	*/
func _vdbePmaReaderSeek(tls *libc.TLS, pTask uintptr, pReadr uintptr, pFile uintptr, iOff Ti64) (r int32) {
	var iBuf, nRead, pgsz, rc int32
	_, _, _, _ = iBuf, nRead, pgsz, rc
	rc = SQLITE_OK
	if _sqlite3FaultSim(tls, int32(201)) != 0 {
		return libc.Int32FromInt32(SQLITE_IOERR) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
	}
	if (*TPmaReader)(unsafe.Pointer(pReadr)).FaMap != 0 {
		_sqlite3OsUnfetch(tls, (*TPmaReader)(unsafe.Pointer(pReadr)).FpFd, 0, (*TPmaReader)(unsafe.Pointer(pReadr)).FaMap)
		(*TPmaReader)(unsafe.Pointer(pReadr)).FaMap = uintptr(0)
	}
	(*TPmaReader)(unsafe.Pointer(pReadr)).FiReadOff = iOff
	(*TPmaReader)(unsafe.Pointer(pReadr)).FiEof = (*TSorterFile)(unsafe.Pointer(pFile)).FiEof
	(*TPmaReader)(unsafe.Pointer(pReadr)).FpFd = (*TSorterFile)(unsafe.Pointer(pFile)).FpFd
	rc = _vdbeSorterMapFile(tls, pTask, pFile, pReadr+44)
	if rc == SQLITE_OK && (*TPmaReader)(unsafe.Pointer(pReadr)).FaMap == uintptr(0) {
		pgsz = (*TVdbeSorter)(unsafe.Pointer((*TSortSubtask)(unsafe.Pointer(pTask)).FpSorter)).Fpgsz
		iBuf = int32((*TPmaReader)(unsafe.Pointer(pReadr)).FiReadOff % int64(pgsz))
		if (*TPmaReader)(unsafe.Pointer(pReadr)).FaBuffer == uintptr(0) {
			(*TPmaReader)(unsafe.Pointer(pReadr)).FaBuffer = _sqlite3Malloc(tls, libc.Uint64FromInt32(pgsz))
			if (*TPmaReader)(unsafe.Pointer(pReadr)).FaBuffer == uintptr(0) {
				rc = int32(SQLITE_NOMEM)
			}
			(*TPmaReader)(unsafe.Pointer(pReadr)).FnBuffer = pgsz
		}
		if rc == SQLITE_OK && iBuf != 0 {
			nRead = pgsz - iBuf
			if (*TPmaReader)(unsafe.Pointer(pReadr)).FiReadOff+int64(nRead) > (*TPmaReader)(unsafe.Pointer(pReadr)).FiEof {
				nRead = int32((*TPmaReader)(unsafe.Pointer(pReadr)).FiEof - (*TPmaReader)(unsafe.Pointer(pReadr)).FiReadOff)
			}
			rc = _sqlite3OsRead(tls, (*TPmaReader)(unsafe.Pointer(pReadr)).FpFd, (*TPmaReader)(unsafe.Pointer(pReadr)).FaBuffer+uintptr(iBuf), nRead, (*TPmaReader)(unsafe.Pointer(pReadr)).FiReadOff)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** This function is an optimized version of sqlite3VdbeRecordCompare()
//	** that (a) the first field of pPKey2 is an integer, and (b) the
//	** size-of-header varint at the start of (pKey1/nKey1) fits in a single
//	** byte (i.e. is less than 128).
//	**
//	** To avoid concerns about buffer overreads, this routine is only used
//	** on schemas where the maximum valid header size is 63 bytes or less.
//	*/
func _vdbeRecordCompareInt(tls *libc.TLS, nKey1 int32, pKey1 uintptr, pPKey2 uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aKey uintptr
	var lhs, v Ti64
	var res, serial_type int32
	var _ /* x at bp+8 */ Tu64
	var _ /* y at bp+0 */ Tu32
	_, _, _, _, _ = aKey, lhs, res, serial_type, v
	aKey = pKey1 + uintptr(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pKey1)))&int32(0x3F))
	serial_type = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pKey1 + 1)))
	switch serial_type {
	case int32(1): /* 1-byte signed integer */
		lhs = int64(libc.Int8FromUint8(**(**Tu8)(__ccgo_up(aKey))))
	case int32(2): /* 2-byte signed integer */
		lhs = int64(libc.Int32FromInt32(256)*int32(libc.Int8FromUint8(**(**Tu8)(__ccgo_up(aKey)))) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 1))))
	case int32(3): /* 3-byte signed integer */
		lhs = int64(libc.Int32FromInt32(65536)*int32(libc.Int8FromUint8(**(**Tu8)(__ccgo_up(aKey)))) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 1)))<<libc.Int32FromInt32(8) | libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 2))))
	case int32(4): /* 4-byte signed integer */
		**(**Tu32)(__ccgo_up(bp)) = uint32(**(**Tu8)(__ccgo_up(aKey)))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**Tu8)(__ccgo_up(aKey + 3)))
		lhs = int64(**(**int32)(__ccgo_up(bp)))
	case int32(5): /* 6-byte signed integer */
		lhs = libc.Int64FromUint32(uint32(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(2))))<<libc.Int32FromInt32(24)|libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(2) + 1)))<<libc.Int32FromInt32(16))|libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(2) + 2)))<<libc.Int32FromInt32(8))|uint32(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(2) + 3)))) + libc.Int64FromInt32(1)<<libc.Int32FromInt32(32)*int64(libc.Int32FromInt32(256)*int32(libc.Int8FromUint8(**(**Tu8)(__ccgo_up(aKey))))|libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 1))))
	case int32(6): /* 8-byte signed integer */
		**(**Tu64)(__ccgo_up(bp + 8)) = uint64(uint32(**(**Tu8)(__ccgo_up(aKey)))<<libc.Int32FromInt32(24) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 1)))<<libc.Int32FromInt32(16)) | libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + 2)))<<libc.Int32FromInt32(8)) | uint32(**(**Tu8)(__ccgo_up(aKey + 3))))
		**(**Tu64)(__ccgo_up(bp + 8)) = **(**Tu64)(__ccgo_up(bp + 8))<<libc.Int32FromInt32(32) | uint64(uint32(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(4))))<<libc.Int32FromInt32(24)|libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(4) + 1)))<<libc.Int32FromInt32(16))|libc.Uint32FromInt32(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(4) + 2)))<<libc.Int32FromInt32(8))|uint32(**(**Tu8)(__ccgo_up(aKey + libc.UintptrFromInt32(4) + 3))))
		lhs = **(**Ti64)(__ccgo_up(bp + 8))
	case int32(8):
		lhs = 0
	case int32(9):
		lhs = int64(1)
		break
		/* This case could be removed without changing the results of running
		 ** this code. Including it causes gcc to generate a faster switch
		 ** statement (since the range of switch targets now starts at zero and
		 ** is contiguous) but does not cause any duplicate code to be generated
		 ** (as gcc is clever enough to combine the two like cases). Other
		 ** compilers might be similar.  */
		fallthrough
	case 0:
		fallthrough
	case int32(7):
		return _sqlite3VdbeRecordCompare(tls, nKey1, pKey1, pPKey2)
	default:
		return _sqlite3VdbeRecordCompare(tls, nKey1, pKey1, pPKey2)
	}
	v = *(*Ti64)(unsafe.Pointer(pPKey2 + 8))
	if v > lhs {
		res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr1)
	} else {
		if v < lhs {
			res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr2)
		} else {
			if libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).FnField) > int32(1) {
				/* The first fields of the two keys are equal. Compare the trailing
				 ** fields.  */
				res = _sqlite3VdbeRecordCompareWithSkip(tls, nKey1, pKey1, pPKey2, int32(1))
			} else {
				/* The first fields of the two keys are equal and there are no trailing
				 ** fields. Return pPKey2->default_rc in this case. */
				res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fdefault_rc)
				(*TUnpackedRecord)(unsafe.Pointer(pPKey2)).FeqSeen = uint8(1)
			}
		}
	}
	return res
}

// C documentation
//
//	/*
//	** This function is an optimized version of sqlite3VdbeRecordCompare()
//	** that (a) the first field of pPKey2 is a string, that (b) the first field
//	** uses the collation sequence BINARY and (c) that the size-of-header varint
//	** at the start of (pKey1/nKey1) fits in a single byte.
//	*/
func _vdbeRecordCompareString(tls *libc.TLS, nKey1 int32, pKey1 uintptr, pPKey2 uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aKey1 uintptr
	var nCmp, nStr, res, szHdr, v1 int32
	var _ /* serial_type at bp+0 */ int32
	_, _, _, _, _, _ = aKey1, nCmp, nStr, res, szHdr, v1
	aKey1 = pKey1
	**(**int32)(__ccgo_up(bp)) = int32(libc.Int8FromUint8(**(**Tu8)(__ccgo_up(aKey1 + 1))))
	goto vrcs_restart
vrcs_restart:
	;
	if **(**int32)(__ccgo_up(bp)) < int32(12) {
		if **(**int32)(__ccgo_up(bp)) < 0 {
			_sqlite3GetVarint32(tls, aKey1+1, bp)
			if **(**int32)(__ccgo_up(bp)) >= int32(12) {
				goto vrcs_restart
			}
		}
		res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr1) /* (pKey1/nKey1) is a number or a null */
	} else {
		if !(**(**int32)(__ccgo_up(bp))&libc.Int32FromInt32(0x01) != 0) {
			res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr2) /* (pKey1/nKey1) is a blob */
		} else {
			szHdr = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(aKey1)))
			nStr = (**(**int32)(__ccgo_up(bp)) - int32(12)) / int32(2)
			if szHdr+nStr > nKey1 {
				(*TUnpackedRecord)(unsafe.Pointer(pPKey2)).FerrCode = libc.Uint8FromInt32(_sqlite3CorruptError(tls, int32(92972)))
				return 0 /* Corruption */
			}
			if (*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fn < nStr {
				v1 = (*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fn
			} else {
				v1 = nStr
			}
			nCmp = v1
			res = libc.Xmemcmp(tls, aKey1+uintptr(szHdr), (*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fu.Fz, libc.Uint32FromInt32(nCmp))
			if res > 0 {
				res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr2)
			} else {
				if res < 0 {
					res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr1)
				} else {
					res = nStr - (*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fn
					if res == 0 {
						if libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).FnField) > int32(1) {
							res = _sqlite3VdbeRecordCompareWithSkip(tls, nKey1, pKey1, pPKey2, int32(1))
						} else {
							res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fdefault_rc)
							(*TUnpackedRecord)(unsafe.Pointer(pPKey2)).FeqSeen = uint8(1)
						}
					} else {
						if res > 0 {
							res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr2)
						} else {
							res = int32((*TUnpackedRecord)(unsafe.Pointer(pPKey2)).Fr1)
						}
					}
				}
			}
		}
	}
	return res
}

// C documentation
//
//	/*
//	** Helper function for vdbeIsMatchingIndexKey(). Return true if column
//	** iCol should be ignored when comparing a record with a record from
//	** an index on disk. The field should be ignored if:
//	**
//	**   * the corresponding bit in mask is set, and
//	**   * either:
//	**       - bIntegrity is false, or
//	**       - the two Mem values are both real values that differ by
//	**         BTREE_ULPDISTORTION or fewer ULPs.
//	*/
func _vdbeSkipField(tls *libc.TLS, mask TBitmask, iCol int32, pMem1 uintptr, pMem2 uintptr, bIntegrity int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var v1 uint64
	var _ /* m1 at bp+0 */ Tu64
	var _ /* m2 at bp+8 */ Tu64
	_ = v1
	if iCol >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8)) || mask&(libc.Uint64FromInt32(1)<<iCol) == uint64(0) {
		return 0
	}
	if bIntegrity == 0 {
		return int32(1)
	}
	if libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem1)).Fflags)&int32(MEM_Real) != 0 && libc.Int32FromUint16((*TMem)(unsafe.Pointer(pMem2)).Fflags)&int32(MEM_Real) != 0 {
		libc.Xmemcpy(tls, bp, pMem1, uint32(8))
		libc.Xmemcpy(tls, bp+8, pMem2, uint32(8))
		if **(**Tu64)(__ccgo_up(bp)) < **(**Tu64)(__ccgo_up(bp + 8)) {
			v1 = **(**Tu64)(__ccgo_up(bp + 8)) - **(**Tu64)(__ccgo_up(bp))
		} else {
			v1 = **(**Tu64)(__ccgo_up(bp)) - **(**Tu64)(__ccgo_up(bp + 8))
		}
		if v1 <= uint64(BTREE_ULPDISTORTION) {
			return int32(1)
		}
	}
	return 0
}

// C documentation
//
//	/*
//	** A specially optimized version of vdbeSorterCompare() that assumes that
//	** the first field of each key is a TEXT value and that the collation
//	** sequence to compare them with is BINARY.
//	*/
func _vdbeSorterCompareText(tls *libc.TLS, pTask uintptr, pbKey2Cached uintptr, pKey1 uintptr, nKey1 int32, pKey2 uintptr, nKey2 int32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var p1, p2, v1, v2 uintptr
	var res, v11 int32
	var _ /* n1 at bp+0 */ int32
	var _ /* n2 at bp+4 */ int32
	_, _, _, _, _, _ = p1, p2, res, v1, v2, v11
	p1 = pKey1
	p2 = pKey2
	v1 = p1 + uintptr(**(**Tu8)(__ccgo_up(p1))) /* Pointer to value 1 */
	v2 = p2 + uintptr(**(**Tu8)(__ccgo_up(p2)))
	**(**int32)(__ccgo_up(bp)) = libc.Int32FromUint32(uint32(**(**Tu8)(__ccgo_up(p1 + 1))))
	if **(**int32)(__ccgo_up(bp)) >= int32(0x80) {
		_sqlite3GetVarint32(tls, p1+1, bp)
	}
	**(**int32)(__ccgo_up(bp + 4)) = libc.Int32FromUint32(uint32(**(**Tu8)(__ccgo_up(p2 + 1))))
	if **(**int32)(__ccgo_up(bp + 4)) >= int32(0x80) {
		_sqlite3GetVarint32(tls, p2+1, bp+4)
	}
	if **(**int32)(__ccgo_up(bp)) < **(**int32)(__ccgo_up(bp + 4)) {
		v11 = **(**int32)(__ccgo_up(bp))
	} else {
		v11 = **(**int32)(__ccgo_up(bp + 4))
	}
	res = libc.Xmemcmp(tls, v1, v2, libc.Uint32FromInt32((v11-int32(13))/int32(2)))
	if res == 0 {
		res = **(**int32)(__ccgo_up(bp)) - **(**int32)(__ccgo_up(bp + 4))
	}
	if res == 0 {
		if libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer((*TVdbeSorter)(unsafe.Pointer((*TSortSubtask)(unsafe.Pointer(pTask)).FpSorter)).FpKeyInfo)).FnKeyField) > int32(1) {
			res = _vdbeSorterCompareTail(tls, pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2)
		}
	} else {
		if **(**Tu8)(__ccgo_up((*TKeyInfo)(unsafe.Pointer((*TVdbeSorter)(unsafe.Pointer((*TSortSubtask)(unsafe.Pointer(pTask)).FpSorter)).FpKeyInfo)).FaSortFlags)) != 0 {
			res = res * -int32(1)
		}
	}
	return res
}

// C documentation
//
//	/*
//	** Sort the linked list of records headed at pTask->pList. Return
//	** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
//	** an error occurs.
//	*/
func _vdbeSorterSort(tls *libc.TLS, pTask uintptr, pList uintptr) (r int32) {
	bp := tls.Alloc(256)
	defer tls.Free(256)
	var i, rc int32
	var p, pNext, v3 uintptr
	var _ /* aSlot at bp+0 */ [64]uintptr
	_, _, _, _, _ = i, p, pNext, rc, v3
	rc = _vdbeSortAllocUnpacked(tls, pTask)
	if rc != SQLITE_OK {
		return rc
	}
	p = (*TSorterList)(unsafe.Pointer(pList)).FpList
	(*TSortSubtask)(unsafe.Pointer(pTask)).FxCompare = _vdbeSorterGetCompare(tls, (*TSortSubtask)(unsafe.Pointer(pTask)).FpSorter)
	libc.Xmemset(tls, bp, 0, uint32(256))
	for p != 0 {
		if (*TSorterList)(unsafe.Pointer(pList)).FaMemory != 0 {
			if p == (*TSorterList)(unsafe.Pointer(pList)).FaMemory {
				pNext = uintptr(0)
			} else {
				pNext = (*TSorterList)(unsafe.Pointer(pList)).FaMemory + uintptr(*(*int32)(unsafe.Pointer(p + 4)))
			}
		} else {
			pNext = *(*uintptr)(unsafe.Pointer(p + 4))
		}
		*(*uintptr)(unsafe.Pointer(p + 4)) = uintptr(0)
		i = 0
		for {
			if !((**(**[64]uintptr)(__ccgo_up(bp)))[i] != 0) {
				break
			}
			p = _vdbeSorterMerge(tls, pTask, p, (**(**[64]uintptr)(__ccgo_up(bp)))[i])
			/* ,--Each aSlot[] holds twice as much as the previous. So we cannot use
			 ** |  up all 64 aSlots[] with only a 64-bit address space.
			 ** v                                                                */
			(**(**[64]uintptr)(__ccgo_up(bp)))[i] = uintptr(0)
			goto _1
		_1:
			;
			i = i + 1
		}
		(**(**[64]uintptr)(__ccgo_up(bp)))[i] = p
		p = pNext
	}
	p = uintptr(0)
	i = 0
	for {
		if !(i < libc.Int32FromUint32(libc.Uint32FromInt64(256)/libc.Uint32FromInt64(4))) {
			break
		}
		if (**(**[64]uintptr)(__ccgo_up(bp)))[i] == uintptr(0) {
			goto _2
		}
		if p != 0 {
			v3 = _vdbeSorterMerge(tls, pTask, p, (**(**[64]uintptr)(__ccgo_up(bp)))[i])
		} else {
			v3 = (**(**[64]uintptr)(__ccgo_up(bp)))[i]
		}
		p = v3
		goto _2
	_2:
		;
		i = i + 1
	}
	(*TSorterList)(unsafe.Pointer(pList)).FpList = p
	return libc.Int32FromUint8((*TUnpackedRecord)(unsafe.Pointer((*TSortSubtask)(unsafe.Pointer(pTask)).FpUnpacked)).FerrCode)
}

// C documentation
//
//	/*
//	** Allocate and populate an UnpackedRecord structure based on the serialized
//	** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
//	** if successful, or a NULL pointer if an OOM error is encountered.
//	*/
func _vdbeUnpackRecord(tls *libc.TLS, pKeyInfo uintptr, nKey int32, pKey uintptr) (r uintptr) {
	var pRet uintptr
	_ = pRet /* Return value */
	pRet = _sqlite3VdbeAllocUnpackedRecord(tls, pKeyInfo)
	if pRet != 0 {
		libc.Xmemset(tls, (*TUnpackedRecord)(unsafe.Pointer(pRet)).FaMem, 0, uint32(40)*libc.Uint32FromInt32(libc.Int32FromUint16((*TKeyInfo)(unsafe.Pointer(pKeyInfo)).FnKeyField)+libc.Int32FromInt32(1)))
		_sqlite3VdbeRecordUnpack(tls, nKey, pKey, pRet)
	}
	return pRet
}

// C documentation
//
//	/*
//	** Open a transaction in a connection where the shared-memory is read-only
//	** and where we cannot verify that there is a separate write-capable connection
//	** on hand to keep the shared-memory up-to-date with the WAL file.
//	**
//	** This can happen, for example, when the shared-memory is implemented by
//	** memory-mapping a *-shm file, where a prior writer has shut down and
//	** left the *-shm file on disk, and now the present connection is trying
//	** to use that database but lacks write permission on the *-shm file.
//	** Other scenarios are also possible, depending on the VFS implementation.
//	**
//	** Precondition:
//	**
//	**    The *-wal file has been read and an appropriate wal-index has been
//	**    constructed in pWal->apWiData[] using heap memory instead of shared
//	**    memory.
//	**
//	** If this function returns SQLITE_OK, then the read transaction has
//	** been successfully opened. In this case output variable (*pChanged)
//	** is set to true before returning if the caller should discard the
//	** contents of the page cache before proceeding. Or, if it returns
//	** WAL_RETRY, then the heap memory wal-index has been discarded and
//	** the caller should retry opening the read transaction from the
//	** beginning (including attempting to map the *-shm file).
//	**
//	** If an error occurs, an SQLite error code is returned.
//	*/
func _walBeginShmUnreliable(tls *libc.TLS, pWal uintptr, pChanged uintptr) (r int32) {
	bp := tls.Alloc(64)
	defer tls.Free(64)
	var aData, aFrame uintptr
	var aSaveCksum [2]Tu32
	var i, rc, szFrame, v1 int32
	var iOffset Ti64
	var _ /* aBuf at bp+8 */ [32]Tu8
	var _ /* nTruncate at bp+48 */ Tu32
	var _ /* pDummy at bp+40 */ uintptr
	var _ /* pgno at bp+44 */ Tu32
	var _ /* szWal at bp+0 */ Ti64
	_, _, _, _, _, _, _, _ = aData, aFrame, aSaveCksum, i, iOffset, rc, szFrame, v1 /* Buffer to load WAL header into */
	aFrame = uintptr(0)                                                             /* Saved copy of pWal->hdr.aFrameCksum */
	/* Take WAL_READ_LOCK(0). This has the effect of preventing any
	 ** writers from running a checkpoint, but does not stop them
	 ** from running recovery.  */
	rc = _walLockShared(tls, pWal, libc.Int32FromInt32(3)+libc.Int32FromInt32(0))
	if rc != SQLITE_OK {
		if rc == int32(SQLITE_BUSY) {
			rc = -int32(1)
		}
		goto begin_unreliable_shm_out
	}
	(*TWal)(unsafe.Pointer(pWal)).FreadLock = 0
	/* Check to see if a separate writer has attached to the shared-memory area,
	 ** thus making the shared-memory "reliable" again.  Do this by invoking
	 ** the xShmMap() routine of the VFS and looking to see if the return
	 ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
	 **
	 ** If the shared-memory is now "reliable" return WAL_RETRY, which will
	 ** cause the heap-memory WAL-index to be discarded and the actual
	 ** shared memory to be used in its place.
	 **
	 ** This step is important because, even though this connection is holding
	 ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
	 ** have already checkpointed the WAL file and, while the current
	 ** is active, wrap the WAL and start overwriting frames that this
	 ** process wants to use.
	 **
	 ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
	 ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
	 ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
	 ** even if some external agent does a "chmod" to make the shared-memory
	 ** writable by us, until sqlite3OsShmUnmap() has been called.
	 ** This is a requirement on the VFS implementation.
	 */
	rc = _sqlite3OsShmMap(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, 0, libc.Int32FromUint32(libc.Uint32FromInt64(2)*libc.Uint32FromInt32(libc.Int32FromInt32(HASHTABLE_NPAGE)*libc.Int32FromInt32(2))+libc.Uint32FromInt32(HASHTABLE_NPAGE)*libc.Uint32FromInt64(4)), 0, bp+40)
	/* SQLITE_OK not possible for read-only connection */
	if rc != libc.Int32FromInt32(SQLITE_READONLY)|libc.Int32FromInt32(5)<<libc.Int32FromInt32(8) {
		if rc == int32(SQLITE_READONLY) {
			v1 = -int32(1)
		} else {
			v1 = rc
		}
		rc = v1
		goto begin_unreliable_shm_out
	}
	/* We reach this point only if the real shared-memory is still unreliable.
	 ** Assume the in-memory WAL-index substitute is correct and load it
	 ** into pWal->hdr.
	 */
	libc.Xmemcpy(tls, pWal+52, _walIndexHdr(tls, pWal), uint32(48))
	/* Make sure some writer hasn't come in and changed the WAL file out
	 ** from under us, then disconnected, while we were not looking.
	 */
	rc = _sqlite3OsFileSize(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, bp)
	if rc != SQLITE_OK {
		goto begin_unreliable_shm_out
	}
	if **(**Ti64)(__ccgo_up(bp)) < int64(WAL_HDRSIZE) {
		/* If the wal file is too small to contain a wal-header and the
		 ** wal-index header has mxFrame==0, then it must be safe to proceed
		 ** reading the database file only. However, the page cache cannot
		 ** be trusted, as a read/write connection may have connected, written
		 ** the db, run a checkpoint, truncated the wal file and disconnected
		 ** since this client's last read transaction.  */
		**(**int32)(__ccgo_up(pChanged)) = int32(1)
		if (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame == uint32(0) {
			v1 = SQLITE_OK
		} else {
			v1 = -int32(1)
		}
		rc = v1
		goto begin_unreliable_shm_out
	}
	/* Check the salt keys at the start of the wal file still match. */
	rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, bp+8, int32(WAL_HDRSIZE), 0)
	if rc != SQLITE_OK {
		goto begin_unreliable_shm_out
	}
	if libc.Xmemcmp(tls, pWal+52+32, bp+8+16, uint32(8)) != 0 {
		/* Some writer has wrapped the WAL file while we were not looking.
		 ** Return WAL_RETRY which will cause the in-memory WAL-index to be
		 ** rebuilt. */
		rc = -int32(1)
		goto begin_unreliable_shm_out
	}
	/* Allocate a buffer to read frames into */
	szFrame = libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage + uint32(WAL_FRAME_HDRSIZE))
	aFrame = Xsqlite3_malloc64(tls, libc.Uint64FromInt32(szFrame))
	if aFrame == uintptr(0) {
		rc = int32(SQLITE_NOMEM)
		goto begin_unreliable_shm_out
	}
	aData = aFrame + 24
	/* Check to see if a complete transaction has been appended to the
	 ** wal file since the heap-memory wal-index was created. If so, the
	 ** heap-memory wal-index is discarded and WAL_RETRY returned to
	 ** the caller.  */
	aSaveCksum[0] = **(**Tu32)(__ccgo_up(pWal + 52 + 24))
	aSaveCksum[int32(1)] = **(**Tu32)(__ccgo_up(pWal + 52 + 24 + 1*4))
	iOffset = libc.Int64FromInt32(WAL_HDRSIZE) + libc.Int64FromUint32((*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame+libc.Uint32FromInt32(1)-libc.Uint32FromInt32(1))*libc.Int64FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage+libc.Uint32FromInt32(WAL_FRAME_HDRSIZE))
	for {
		if !(iOffset+int64(szFrame) <= **(**Ti64)(__ccgo_up(bp))) {
			break
		} /* dbsize field from frame header */
		/* Read and decode the next log frame. */
		rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, aFrame, szFrame, iOffset)
		if rc != SQLITE_OK {
			break
		}
		if !(_walDecodeFrame(tls, pWal, bp+44, bp+48, aData, aFrame) != 0) {
			break
		}
		/* If nTruncate is non-zero, then a complete transaction has been
		 ** appended to this wal file. Set rc to WAL_RETRY and break out of
		 ** the loop.  */
		if **(**Tu32)(__ccgo_up(bp + 48)) != 0 {
			rc = -int32(1)
			break
		}
		goto _3
	_3:
		;
		iOffset = iOffset + int64(szFrame)
	}
	**(**Tu32)(__ccgo_up(pWal + 52 + 24)) = aSaveCksum[0]
	**(**Tu32)(__ccgo_up(pWal + 52 + 24 + 1*4)) = aSaveCksum[int32(1)]
	goto begin_unreliable_shm_out
begin_unreliable_shm_out:
	;
	Xsqlite3_free(tls, aFrame)
	if rc != SQLITE_OK {
		i = 0
		for {
			if !(i < (*TWal)(unsafe.Pointer(pWal)).FnWiData) {
				break
			}
			Xsqlite3_free(tls, **(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(i)*4)))
			**(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(i)*4)) = uintptr(0)
			goto _4
		_4:
			;
			i = i + 1
		}
		(*TWal)(unsafe.Pointer(pWal)).FbShmUnreliable = uint8(0)
		_sqlite3WalEndReadTransaction(tls, pWal)
		**(**int32)(__ccgo_up(pChanged)) = int32(1)
	}
	return rc
}

/*
** The final argument passed to walTryBeginRead() is of type (int*). The
** caller should invoke walTryBeginRead as follows:
**
**   int cnt = 0;
**   do {
**     rc = walTryBeginRead(..., &cnt);
**   }while( rc==WAL_RETRY );
**
** The final value of "cnt" is of no use to the caller. It is used by
** the implementation of walTryBeginRead() as follows:
**
**   + Each time walTryBeginRead() is called, it is incremented. Once
**     it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
**     has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
**     returns SQLITE_PROTOCOL.
**
**   + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed
**     because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS
**     layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case
**     the next invocation of walTryBeginRead() may omit an expected call to
**     sqlite3OsSleep(). There has already been a delay when the previous call
**     waited on a lock.
 */

// C documentation
//
//	/*
//	** Remove entries from the hash table that point to WAL slots greater
//	** than pWal->hdr.mxFrame.
//	**
//	** This function is called whenever pWal->hdr.mxFrame is decreased due
//	** to a rollback or savepoint.
//	**
//	** At most only the hash table containing pWal->hdr.mxFrame needs to be
//	** updated.  Any later hash tables will be automatically cleared when
//	** pWal->hdr.mxFrame advances to the point where those hash tables are
//	** actually needed.
//	*/
func _walCleanupHash(tls *libc.TLS, pWal uintptr) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, iLimit, nByte int32
	var _ /* sLoc at bp+0 */ TWalHashLoc
	_, _, _ = i, iLimit, nByte /* Hash table location */
	iLimit = 0                 /* Used to iterate through aHash[] */
	if (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame == uint32(0) {
		return
	}
	/* Obtain pointers to the hash-table and page-number array containing
	 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
	 ** that the page said hash-table and array reside on is already mapped.(1)
	 */
	i = _walHashGet(tls, pWal, _walFramePage(tls, (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame), bp)
	if i != 0 {
		return
	} /* Defense-in-depth, in case (1) above is wrong */
	/* Zero all hash-table entries that correspond to frame numbers greater
	 ** than pWal->hdr.mxFrame.
	 */
	iLimit = libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame - (**(**TWalHashLoc)(__ccgo_up(bp))).FiZero)
	i = 0
	for {
		if !(i < libc.Int32FromInt32(HASHTABLE_NPAGE)*libc.Int32FromInt32(2)) {
			break
		}
		if libc.Int32FromUint16(**(**Tht_slot)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash + uintptr(i)*2))) > iLimit {
			**(**Tht_slot)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash + uintptr(i)*2)) = uint16(0)
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	/* Zero the entries in the aPgno array that correspond to frames with
	 ** frame numbers greater than pWal->hdr.mxFrame.
	 */
	nByte = int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash) - int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno+uintptr(iLimit)*4)
	libc.Xmemset(tls, (**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno+uintptr(iLimit)*4, 0, libc.Uint32FromInt32(nByte))
}

// C documentation
//
//	/*
//	** Check to see if the frame with header in aFrame[] and content
//	** in aData[] is valid.  If it is a valid frame, fill *piPage and
//	** *pnTruncate and return true.  Return if the frame is not valid.
//	*/
func _walDecodeFrame(tls *libc.TLS, pWal uintptr, piPage uintptr, pnTruncate uintptr, aData uintptr, aFrame uintptr) (r int32) {
	var aCksum uintptr
	var nativeCksum int32
	var pgno Tu32
	_, _, _ = aCksum, nativeCksum, pgno /* True for native byte-order checksums */
	aCksum = pWal + 52 + 24             /* Page number of the frame */
	/* A frame is only valid if the salt values in the frame-header
	 ** match the salt values in the wal-header.
	 */
	if libc.Xmemcmp(tls, pWal+52+32, aFrame+8, uint32(8)) != 0 {
		return 0
	}
	/* A frame is only valid if the page number is greater than zero.
	 */
	pgno = _sqlite3Get4byte(tls, aFrame)
	if pgno == uint32(0) {
		return 0
	}
	/* Need a valid page size
	 */
	if !((*TWal)(unsafe.Pointer(pWal)).FszPage != 0) {
		return 0
	}
	/* A frame is only valid if a checksum of the WAL header,
	 ** all prior frames, the first 16 bytes of this frame-header,
	 ** and the frame-data matches the checksum in the last 8
	 ** bytes of this frame-header.
	 */
	nativeCksum = libc.BoolInt32(libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).Fhdr.FbigEndCksum) == SQLITE_BIGENDIAN)
	_walChecksumBytes(tls, nativeCksum, aFrame, int32(8), aCksum, aCksum)
	_walChecksumBytes(tls, nativeCksum, aData, libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage), aCksum, aCksum)
	if **(**Tu32)(__ccgo_up(aCksum)) != _sqlite3Get4byte(tls, aFrame+16) || **(**Tu32)(__ccgo_up(aCksum + 1*4)) != _sqlite3Get4byte(tls, aFrame+20) {
		/* Checksum failed. */
		return 0
	}
	/* If we reach this point, the frame is valid.  Return the page number
	 ** and the new database size.
	 */
	**(**Tu32)(__ccgo_up(piPage)) = pgno
	**(**Tu32)(__ccgo_up(pnTruncate)) = _sqlite3Get4byte(tls, aFrame+4)
	return int32(1)
}

// C documentation
//
//	/*
//	** This function encodes a single frame header and writes it to a buffer
//	** supplied by the caller. A frame-header is made up of a series of
//	** 4-byte big-endian integers, as follows:
//	**
//	**     0: Page number.
//	**     4: For commit records, the size of the database image in pages
//	**        after the commit. For all other records, zero.
//	**     8: Salt-1 (copied from the wal-header)
//	**    12: Salt-2 (copied from the wal-header)
//	**    16: Checksum-1.
//	**    20: Checksum-2.
//	*/
func _walEncodeFrame(tls *libc.TLS, pWal uintptr, iPage Tu32, nTruncate Tu32, aData uintptr, aFrame uintptr) {
	var aCksum uintptr
	var nativeCksum int32
	_, _ = aCksum, nativeCksum /* True for native byte-order checksums */
	aCksum = pWal + 52 + 24
	_sqlite3Put4byte(tls, aFrame, iPage)
	_sqlite3Put4byte(tls, aFrame+4, nTruncate)
	if (*TWal)(unsafe.Pointer(pWal)).FiReCksum == uint32(0) {
		libc.Xmemcpy(tls, aFrame+8, pWal+52+32, uint32(8))
		nativeCksum = libc.BoolInt32(libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).Fhdr.FbigEndCksum) == SQLITE_BIGENDIAN)
		_walChecksumBytes(tls, nativeCksum, aFrame, int32(8), aCksum, aCksum)
		_walChecksumBytes(tls, nativeCksum, aData, libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage), aCksum, aCksum)
		_sqlite3Put4byte(tls, aFrame+16, **(**Tu32)(__ccgo_up(aCksum)))
		_sqlite3Put4byte(tls, aFrame+20, **(**Tu32)(__ccgo_up(aCksum + 1*4)))
	} else {
		libc.Xmemset(tls, aFrame+8, 0, uint32(16))
	}
}

// C documentation
//
//	/*
//	** Search the wal file for page pgno. If found, set *piRead to the frame that
//	** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
//	** to zero.
//	**
//	** Return SQLITE_OK if successful, or an error code if an error occurs. If an
//	** error does occur, the final value of *piRead is undefined.
//	*/
func _walFindFrame(tls *libc.TLS, pWal uintptr, pgno TPgno, piRead uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iFrame, iH, iLast, iRead, v2 Tu32
	var iHash, iKey, iMinHash, nCollide, rc, v3 int32
	var _ /* sLoc at bp+0 */ TWalHashLoc
	_, _, _, _, _, _, _, _, _, _, _ = iFrame, iH, iHash, iKey, iLast, iMinHash, iRead, nCollide, rc, v2, v3
	iRead = uint32(0) /* If !=0, WAL frame to return data from */
	iLast = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame
	/* This routine is only be called from within a read transaction. */
	/* If the "last page" field of the wal-index header snapshot is 0, then
	 ** no data will be read from the wal under any circumstances. Return early
	 ** in this case as an optimization.  Likewise, if pWal->readLock==0,
	 ** then the WAL is ignored by the reader so return early, as if the
	 ** WAL were empty.
	 */
	if iLast == uint32(0) || int32((*TWal)(unsafe.Pointer(pWal)).FreadLock) == 0 && libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FbShmUnreliable) == 0 {
		**(**Tu32)(__ccgo_up(piRead)) = uint32(0)
		return SQLITE_OK
	}
	/* Search the hash table or tables for an entry matching page number
	 ** pgno. Each iteration of the following for() loop searches one
	 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
	 **
	 ** This code might run concurrently to the code in walIndexAppend()
	 ** that adds entries to the wal-index (and possibly to this hash
	 ** table). This means the value just read from the hash
	 ** slot (aHash[iKey]) may have been added before or after the
	 ** current read transaction was opened. Values added after the
	 ** read transaction was opened may have been written incorrectly -
	 ** i.e. these slots may contain garbage data. However, we assume
	 ** that any slots written before the current read transaction was
	 ** opened remain unmodified.
	 **
	 ** For the reasons above, the if(...) condition featured in the inner
	 ** loop of the following block is more stringent that would be required
	 ** if we had exclusive access to the hash-table:
	 **
	 **   (aPgno[iFrame]==pgno):
	 **     This condition filters out normal hash-table collisions.
	 **
	 **   (iFrame<=iLast):
	 **     This condition filters out entries that were added to the hash
	 **     table after the current read-transaction had started.
	 */
	iMinHash = _walFramePage(tls, (*TWal)(unsafe.Pointer(pWal)).FminFrame)
	iHash = _walFramePage(tls, iLast)
	for {
		if !(iHash >= iMinHash) {
			break
		}
		rc = _walHashGet(tls, pWal, iHash, bp)
		if rc != SQLITE_OK {
			return rc
		}
		nCollide = libc.Int32FromInt32(HASHTABLE_NPAGE) * libc.Int32FromInt32(2)
		iKey = _walHash(tls, pgno)
		for {
			v2 = uint32(libc.AtomicLoadNUint16((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash+uintptr(iKey)*2, libc.Int32FromInt32(__ATOMIC_RELAXED)))
			iH = v2
			if !(v2 != uint32(0)) {
				break
			}
			iFrame = iH + (**(**TWalHashLoc)(__ccgo_up(bp))).FiZero
			if iFrame <= iLast && iFrame >= (*TWal)(unsafe.Pointer(pWal)).FminFrame && **(**Tu32)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno + uintptr((iH-uint32(1))&libc.Uint32FromInt32(libc.Int32FromInt32(HASHTABLE_NPAGE)-libc.Int32FromInt32(1)))*4)) == pgno {
				iRead = iFrame
			}
			v3 = nCollide
			nCollide = nCollide - 1
			if v3 == 0 {
				**(**Tu32)(__ccgo_up(piRead)) = uint32(0)
				return _sqlite3CorruptError(tls, int32(71119))
			}
			iKey = _walNextHash(tls, iKey)
		}
		if iRead != 0 {
			break
		}
		goto _1
	_1:
		;
		iHash = iHash - 1
	}
	**(**Tu32)(__ccgo_up(piRead)) = iRead
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Return the number of the wal-index page that contains the hash-table
//	** and page-number array that contain entries corresponding to WAL frame
//	** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
//	** are numbered starting from 0.
//	*/
func _walFramePage(tls *libc.TLS, iFrame Tu32) (r int32) {
	var iHash int32
	_ = iHash
	iHash = libc.Int32FromUint32((iFrame + uint32(HASHTABLE_NPAGE) - (libc.Uint32FromInt32(HASHTABLE_NPAGE) - (libc.Uint32FromInt64(48)*libc.Uint32FromInt32(2)+libc.Uint32FromInt64(40))/libc.Uint32FromInt64(4)) - uint32(1)) / uint32(HASHTABLE_NPAGE))
	return iHash
}

// C documentation
//
//	/*
//	** Write a set of frames to the log. The caller must hold the write-lock
//	** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
//	*/
func _walFrames(tls *libc.TLS, pWal uintptr, szPage int32, pList uintptr, nTruncate TPgno, isCommit int32, sync_flags int32) (r int32) {
	bp := tls.Alloc(80)
	defer tls.Free(80)
	var bSync, nDbSize, nExtra, rc, sectorSize, szFrame, v1 int32
	var iFirst, iFrame Tu32
	var iOff, iOffset, sz Ti64
	var p, pData, pLast, pLive, v3 uintptr
	var v4 uint32
	var _ /* aCksum at bp+56 */ [2]Tu32
	var _ /* aWalHdr at bp+24 */ [32]Tu8
	var _ /* iWrite at bp+64 */ Tu32
	var _ /* w at bp+0 */ TWalWriter
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = bSync, iFirst, iFrame, iOff, iOffset, nDbSize, nExtra, p, pData, pLast, pLive, rc, sectorSize, sz, szFrame, v1, v3, v4 /* Iterator to run through pList with. */
	pLast = uintptr(0)                                                                                                                                                            /* Last frame in list */
	nExtra = 0                                                                                                                                                                    /* The writer */
	iFirst = uint32(0)                                                                                                                                                            /* Pointer to shared header */
	/* If this frame set completes a transaction, then nTruncate>0.  If
	 ** nTruncate==0 then this frame set does not complete the transaction. */
	pLive = _walIndexHdr(tls, pWal)
	if libc.Xmemcmp(tls, pWal+52, pLive, uint32(48)) != 0 {
		iFirst = (*TWalIndexHdr)(unsafe.Pointer(pLive)).FmxFrame + uint32(1)
	}
	/* See if it is possible to write these frames into the start of the
	 ** log file, instead of appending to it at pWal->hdr.mxFrame.
	 */
	v1 = _walRestartLog(tls, pWal)
	rc = v1
	if SQLITE_OK != v1 {
		return rc
	}
	/* If this is the first frame written into the log, write the WAL
	 ** header to the start of the WAL file. See comments at the top of
	 ** this source file for a description of the WAL header format.
	 */
	iFrame = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame
	if iFrame == uint32(0) { /* Checksum for wal-header */
		_sqlite3Put4byte(tls, bp+24, libc.Uint32FromInt32(libc.Int32FromInt32(WAL_MAGIC)|libc.Int32FromInt32(SQLITE_BIGENDIAN)))
		_sqlite3Put4byte(tls, bp+24+4, uint32(WAL_MAX_VERSION))
		_sqlite3Put4byte(tls, bp+24+8, libc.Uint32FromInt32(szPage))
		_sqlite3Put4byte(tls, bp+24+12, (*TWal)(unsafe.Pointer(pWal)).FnCkpt)
		if (*TWal)(unsafe.Pointer(pWal)).FnCkpt == uint32(0) {
			Xsqlite3_randomness(tls, int32(8), pWal+52+32)
		}
		libc.Xmemcpy(tls, bp+24+16, pWal+52+32, uint32(8))
		_walChecksumBytes(tls, int32(1), bp+24, libc.Int32FromInt32(WAL_HDRSIZE)-libc.Int32FromInt32(2)*libc.Int32FromInt32(4), uintptr(0), bp+56)
		_sqlite3Put4byte(tls, bp+24+24, (**(**[2]Tu32)(__ccgo_up(bp + 56)))[0])
		_sqlite3Put4byte(tls, bp+24+28, (**(**[2]Tu32)(__ccgo_up(bp + 56)))[int32(1)])
		(*TWal)(unsafe.Pointer(pWal)).FszPage = libc.Uint32FromInt32(szPage)
		(*TWal)(unsafe.Pointer(pWal)).Fhdr.FbigEndCksum = uint8(SQLITE_BIGENDIAN)
		**(**Tu32)(__ccgo_up(pWal + 52 + 24)) = (**(**[2]Tu32)(__ccgo_up(bp + 56)))[0]
		**(**Tu32)(__ccgo_up(pWal + 52 + 24 + 1*4)) = (**(**[2]Tu32)(__ccgo_up(bp + 56)))[int32(1)]
		(*TWal)(unsafe.Pointer(pWal)).FtruncateOnCommit = uint8(1)
		rc = _sqlite3OsWrite(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, bp+24, int32(32), 0)
		if rc != SQLITE_OK {
			return rc
		}
		/* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
		 ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
		 ** an out-of-order write following a WAL restart could result in
		 ** database corruption.  See the ticket:
		 **
		 **     https://sqlite.org/src/info/ff5be73dee
		 */
		if (*TWal)(unsafe.Pointer(pWal)).FsyncHeader != 0 {
			rc = _sqlite3OsSync(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, sync_flags>>int32(2)&int32(0x03))
			if rc != 0 {
				return rc
			}
		}
	}
	if libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage) != szPage {
		return _sqlite3CorruptError(tls, int32(71646)) /* TH3 test case: cov1/corrupt155.test */
	}
	/* Setup information needed to write frames into the WAL */
	(**(**TWalWriter)(__ccgo_up(bp))).FpWal = pWal
	(**(**TWalWriter)(__ccgo_up(bp))).FpFd = (*TWal)(unsafe.Pointer(pWal)).FpWalFd
	(**(**TWalWriter)(__ccgo_up(bp))).FiSyncPoint = 0
	(**(**TWalWriter)(__ccgo_up(bp))).FsyncFlags = sync_flags
	(**(**TWalWriter)(__ccgo_up(bp))).FszPage = szPage
	iOffset = libc.Int64FromInt32(WAL_HDRSIZE) + libc.Int64FromUint32(iFrame+libc.Uint32FromInt32(1)-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE))
	szFrame = szPage + int32(WAL_FRAME_HDRSIZE)
	/* Write all frames into the log file exactly once */
	p = pList
	for {
		if !(p != 0) {
			break
		} /* 0 normally.  Positive == commit flag */
		/* Check if this page has already been written into the wal file by
		 ** the current transaction. If so, overwrite the existing frame and
		 ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
		 ** checksums must be recomputed when the transaction is committed.  */
		if iFirst != 0 && ((*TPgHdr)(unsafe.Pointer(p)).FpDirty != 0 || isCommit == 0) {
			**(**Tu32)(__ccgo_up(bp + 64)) = uint32(0)
			_walFindFrame(tls, pWal, (*TPgHdr)(unsafe.Pointer(p)).Fpgno, bp+64)
			if **(**Tu32)(__ccgo_up(bp + 64)) >= iFirst {
				iOff = int64(WAL_HDRSIZE) + libc.Int64FromUint32(**(**Tu32)(__ccgo_up(bp + 64))-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE)) + int64(WAL_FRAME_HDRSIZE)
				if (*TWal)(unsafe.Pointer(pWal)).FiReCksum == uint32(0) || **(**Tu32)(__ccgo_up(bp + 64)) < (*TWal)(unsafe.Pointer(pWal)).FiReCksum {
					(*TWal)(unsafe.Pointer(pWal)).FiReCksum = **(**Tu32)(__ccgo_up(bp + 64))
				}
				pData = (*TPgHdr)(unsafe.Pointer(p)).FpData
				rc = _sqlite3OsWrite(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, pData, szPage, iOff)
				if rc != 0 {
					return rc
				}
				v3 = p + 28
				*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) & ^libc.Int32FromInt32(PGHDR_WAL_APPEND))
				goto _2
			}
		}
		iFrame = iFrame + 1
		if isCommit != 0 && (*TPgHdr)(unsafe.Pointer(p)).FpDirty == uintptr(0) {
			v4 = nTruncate
		} else {
			v4 = uint32(0)
		}
		nDbSize = libc.Int32FromUint32(v4)
		rc = _walWriteOneFrame(tls, bp, p, nDbSize, iOffset)
		if rc != 0 {
			return rc
		}
		pLast = p
		iOffset = iOffset + int64(szFrame)
		v3 = p + 28
		*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromInt32(PGHDR_WAL_APPEND))
		goto _2
	_2:
		;
		p = (*TPgHdr)(unsafe.Pointer(p)).FpDirty
	}
	/* Recalculate checksums within the wal file if required. */
	if isCommit != 0 && (*TWal)(unsafe.Pointer(pWal)).FiReCksum != 0 {
		rc = _walRewriteChecksums(tls, pWal, iFrame)
		if rc != 0 {
			return rc
		}
	}
	/* If this is the end of a transaction, then we might need to pad
	 ** the transaction and/or sync the WAL file.
	 **
	 ** Padding and syncing only occur if this set of frames complete a
	 ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
	 ** or synchronous==OFF, then no padding or syncing are needed.
	 **
	 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
	 ** needed and only the sync is done.  If padding is needed, then the
	 ** final frame is repeated (with its commit mark) until the next sector
	 ** boundary is crossed.  Only the part of the WAL prior to the last
	 ** sector boundary is synced; the part of the last frame that extends
	 ** past the sector boundary is written after the sync.
	 */
	if isCommit != 0 && sync_flags&int32(0x03) != 0 {
		bSync = int32(1)
		if (*TWal)(unsafe.Pointer(pWal)).FpadToSectorBoundary != 0 {
			sectorSize = _sqlite3SectorSize(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd)
			(**(**TWalWriter)(__ccgo_up(bp))).FiSyncPoint = (iOffset + int64(sectorSize) - int64(1)) / int64(sectorSize) * int64(sectorSize)
			bSync = libc.BoolInt32((**(**TWalWriter)(__ccgo_up(bp))).FiSyncPoint == iOffset)
			for iOffset < (**(**TWalWriter)(__ccgo_up(bp))).FiSyncPoint {
				rc = _walWriteOneFrame(tls, bp, pLast, libc.Int32FromUint32(nTruncate), iOffset)
				if rc != 0 {
					return rc
				}
				iOffset = iOffset + int64(szFrame)
				nExtra = nExtra + 1
			}
		}
		if bSync != 0 {
			rc = _sqlite3OsSync(tls, (**(**TWalWriter)(__ccgo_up(bp))).FpFd, sync_flags&int32(0x03))
		}
	}
	/* If this frame set completes the first transaction in the WAL and
	 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
	 ** journal size limit, if possible.
	 */
	if isCommit != 0 && (*TWal)(unsafe.Pointer(pWal)).FtruncateOnCommit != 0 && (*TWal)(unsafe.Pointer(pWal)).FmxWalSize >= 0 {
		sz = (*TWal)(unsafe.Pointer(pWal)).FmxWalSize
		if int64(WAL_HDRSIZE)+libc.Int64FromUint32(iFrame+libc.Uint32FromInt32(nExtra)+libc.Uint32FromInt32(1)-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE)) > (*TWal)(unsafe.Pointer(pWal)).FmxWalSize {
			sz = libc.Int64FromInt32(WAL_HDRSIZE) + libc.Int64FromUint32(iFrame+libc.Uint32FromInt32(nExtra)+libc.Uint32FromInt32(1)-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE))
		}
		_walLimitSize(tls, pWal, sz)
		(*TWal)(unsafe.Pointer(pWal)).FtruncateOnCommit = uint8(0)
	}
	/* Append data to the wal-index. It is not necessary to lock the
	 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
	 ** guarantees that there are no other writers, and no data that may
	 ** be in use by existing readers is being overwritten.
	 */
	iFrame = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame
	p = pList
	for {
		if !(p != 0 && rc == SQLITE_OK) {
			break
		}
		if libc.Int32FromUint16((*TPgHdr)(unsafe.Pointer(p)).Fflags)&int32(PGHDR_WAL_APPEND) == 0 {
			goto _6
		}
		iFrame = iFrame + 1
		rc = _walIndexAppend(tls, pWal, iFrame, (*TPgHdr)(unsafe.Pointer(p)).Fpgno)
		goto _6
	_6:
		;
		p = (*TPgHdr)(unsafe.Pointer(p)).FpDirty
	}
	for rc == SQLITE_OK && nExtra > 0 {
		iFrame = iFrame + 1
		nExtra = nExtra - 1
		rc = _walIndexAppend(tls, pWal, iFrame, (*TPgHdr)(unsafe.Pointer(pLast)).Fpgno)
	}
	if rc == SQLITE_OK {
		/* Update the private copy of the header. */
		(*TWal)(unsafe.Pointer(pWal)).Fhdr.FszPage = libc.Uint16FromInt32(szPage&libc.Int32FromInt32(0xff00) | szPage>>libc.Int32FromInt32(16))
		(*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame = iFrame
		if isCommit != 0 {
			(*TWal)(unsafe.Pointer(pWal)).Fhdr.FiChange = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FiChange + 1
			(*TWal)(unsafe.Pointer(pWal)).Fhdr.FnPage = nTruncate
		}
		/* If this is a commit, update the wal-index header too. */
		if isCommit != 0 {
			_walIndexWriteHdr(tls, pWal)
			(*TWal)(unsafe.Pointer(pWal)).FiCallback = iFrame
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Return pointers to the hash table and page number array stored on
//	** page iHash of the wal-index. The wal-index is broken into 32KB pages
//	** numbered starting from 0.
//	**
//	** Set output variable pLoc->aHash to point to the start of the hash table
//	** in the wal-index file. Set pLoc->iZero to one less than the frame
//	** number of the first frame indexed by this hash table. If a
//	** slot in the hash table is set to N, it refers to frame number
//	** (pLoc->iZero+N) in the log.
//	**
//	** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
//	** first frame indexed by the hash table, frame (pLoc->iZero).
//	*/
func _walHashGet(tls *libc.TLS, pWal uintptr, iHash int32, pLoc uintptr) (r int32) {
	var rc int32
	_ = rc /* Return code */
	rc = _walIndexPage(tls, pWal, iHash, pLoc+4)
	if (*TWalHashLoc)(unsafe.Pointer(pLoc)).FaPgno != 0 {
		(*TWalHashLoc)(unsafe.Pointer(pLoc)).FaHash = (*TWalHashLoc)(unsafe.Pointer(pLoc)).FaPgno + 4096*4
		if iHash == 0 {
			(*TWalHashLoc)(unsafe.Pointer(pLoc)).FaPgno = (*TWalHashLoc)(unsafe.Pointer(pLoc)).FaPgno + uintptr((libc.Uint32FromInt64(48)*libc.Uint32FromInt32(2)+libc.Uint32FromInt64(40))/libc.Uint32FromInt64(4))*4
			(*TWalHashLoc)(unsafe.Pointer(pLoc)).FiZero = uint32(0)
		} else {
			(*TWalHashLoc)(unsafe.Pointer(pLoc)).FiZero = libc.Uint32FromInt32(HASHTABLE_NPAGE) - (libc.Uint32FromInt64(48)*libc.Uint32FromInt32(2)+libc.Uint32FromInt64(40))/libc.Uint32FromInt64(4) + libc.Uint32FromInt32((iHash-int32(1))*int32(HASHTABLE_NPAGE))
		}
	} else {
		if rc == SQLITE_OK {
			rc = int32(SQLITE_ERROR)
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Set an entry in the wal-index that will map database page number
//	** pPage into WAL frame iFrame.
//	*/
func _walIndexAppend(tls *libc.TLS, pWal uintptr, iFrame Tu32, iPage Tu32) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var iKey, idx, nByte, nCollide, rc, v2 int32
	var _ /* sLoc at bp+0 */ TWalHashLoc
	_, _, _, _, _, _ = iKey, idx, nByte, nCollide, rc, v2 /* Wal-index hash table location */
	rc = _walHashGet(tls, pWal, _walFramePage(tls, iFrame), bp)
	/* Assuming the wal-index file was successfully mapped, populate the
	 ** page number array and hash table entry.
	 */
	if rc == SQLITE_OK { /* Number of hash collisions */
		idx = libc.Int32FromUint32(iFrame - (**(**TWalHashLoc)(__ccgo_up(bp))).FiZero)
		/* If this is the first entry to be added to this hash-table, zero the
		 ** entire hash table and aPgno[] array before proceeding.
		 */
		if idx == int32(1) {
			nByte = int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash+uintptr(libc.Int32FromInt32(HASHTABLE_NPAGE)*libc.Int32FromInt32(2))*2) - int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno)
			libc.Xmemset(tls, (**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno, 0, libc.Uint32FromInt32(nByte))
		}
		/* If the entry in aPgno[] is already set, then the previous writer
		 ** must have exited unexpectedly in the middle of a transaction (after
		 ** writing one or more dirty pages to the WAL to free up memory).
		 ** Remove the remnants of that writers uncommitted transaction from
		 ** the hash-table before writing any new entries.
		 */
		if **(**Tu32)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno + uintptr(idx-int32(1))*4)) != 0 {
			_walCleanupHash(tls, pWal)
		}
		/* Write the aPgno[] array entry and the hash-table slot. */
		nCollide = idx
		iKey = _walHash(tls, iPage)
		for {
			if !(**(**Tht_slot)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash + uintptr(iKey)*2)) != 0) {
				break
			}
			v2 = nCollide
			nCollide = nCollide - 1
			if v2 == 0 {
				return _sqlite3CorruptError(tls, int32(68860))
			}
			goto _1
		_1:
			;
			iKey = _walNextHash(tls, iKey)
		}
		**(**Tu32)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno + uintptr((idx-int32(1))&(libc.Int32FromInt32(HASHTABLE_NPAGE)-libc.Int32FromInt32(1)))*4)) = iPage
		libc.AtomicStoreNUint16((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash+uintptr(iKey)*2, libc.Uint16FromInt32(idx), libc.Int32FromInt32(__ATOMIC_RELAXED))
	}
	return rc
}

// C documentation
//
//	/*
//	** Close an open wal-index.
//	*/
func _walIndexClose(tls *libc.TLS, pWal uintptr, isDelete int32) {
	var i int32
	_ = i
	if libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FexclusiveMode) == int32(WAL_HEAPMEMORY_MODE) || (*TWal)(unsafe.Pointer(pWal)).FbShmUnreliable != 0 {
		i = 0
		for {
			if !(i < (*TWal)(unsafe.Pointer(pWal)).FnWiData) {
				break
			}
			Xsqlite3_free(tls, **(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(i)*4)))
			**(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(i)*4)) = uintptr(0)
			goto _1
		_1:
			;
			i = i + 1
		}
	}
	if libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FexclusiveMode) != int32(WAL_HEAPMEMORY_MODE) {
		_sqlite3OsShmUnmap(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, isDelete)
	}
}

// C documentation
//
//	/*
//	** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
//	** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
//	** numbered from zero.
//	**
//	** If the wal-index is currently smaller the iPage pages then the size
//	** of the wal-index might be increased, but only if it is safe to do
//	** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
//	** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
//	**
//	** Three possible result scenarios:
//	**
//	**   (1)  rc==SQLITE_OK    and *ppPage==Requested-Wal-Index-Page
//	**   (2)  rc>=SQLITE_ERROR and *ppPage==NULL
//	**   (3)  rc==SQLITE_OK    and *ppPage==NULL  // only if iPage==0
//	**
//	** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
//	*/
func _walIndexPageRealloc(tls *libc.TLS, pWal uintptr, iPage int32, ppPage uintptr) (r int32) {
	var apNew, v1 uintptr
	var nByte Tsqlite3_int64
	var rc int32
	_, _, _, _ = apNew, nByte, rc, v1
	rc = SQLITE_OK
	/* Enlarge the pWal->apWiData[] array if required */
	if (*TWal)(unsafe.Pointer(pWal)).FnWiData <= iPage {
		nByte = int64(4) * (int64(1) + int64(iPage))
		apNew = _sqlite3Realloc(tls, (*TWal)(unsafe.Pointer(pWal)).FapWiData, libc.Uint64FromInt64(nByte))
		if !(apNew != 0) {
			**(**uintptr)(__ccgo_up(ppPage)) = uintptr(0)
			return int32(SQLITE_NOMEM)
		}
		libc.Xmemset(tls, apNew+uintptr((*TWal)(unsafe.Pointer(pWal)).FnWiData)*4, 0, uint32(4)*libc.Uint32FromInt32(iPage+libc.Int32FromInt32(1)-(*TWal)(unsafe.Pointer(pWal)).FnWiData))
		(*TWal)(unsafe.Pointer(pWal)).FapWiData = apNew
		(*TWal)(unsafe.Pointer(pWal)).FnWiData = iPage + int32(1)
	}
	/* Request a pointer to the required page from the VFS */
	if libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FexclusiveMode) == int32(WAL_HEAPMEMORY_MODE) {
		**(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(iPage)*4)) = _sqlite3MallocZero(tls, uint64(libc.Uint32FromInt64(2)*libc.Uint32FromInt32(libc.Int32FromInt32(HASHTABLE_NPAGE)*libc.Int32FromInt32(2))+libc.Uint32FromInt32(HASHTABLE_NPAGE)*libc.Uint32FromInt64(4)))
		if !(**(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(iPage)*4)) != 0) {
			rc = int32(SQLITE_NOMEM)
		}
	} else {
		rc = _sqlite3OsShmMap(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, iPage, libc.Int32FromUint32(libc.Uint32FromInt64(2)*libc.Uint32FromInt32(libc.Int32FromInt32(HASHTABLE_NPAGE)*libc.Int32FromInt32(2))+libc.Uint32FromInt32(HASHTABLE_NPAGE)*libc.Uint32FromInt64(4)), libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FwriteLock), (*TWal)(unsafe.Pointer(pWal)).FapWiData+uintptr(iPage)*4)
		if rc == SQLITE_OK {
			if iPage > 0 && _sqlite3FaultSim(tls, int32(600)) != 0 {
				rc = int32(SQLITE_NOMEM)
			}
		} else {
			if rc&int32(0xff) == int32(SQLITE_READONLY) {
				v1 = pWal + 46
				*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) | libc.Int32FromInt32(WAL_SHM_RDONLY))
				if rc == int32(SQLITE_READONLY) {
					rc = SQLITE_OK
				}
			}
		}
	}
	**(**uintptr)(__ccgo_up(ppPage)) = **(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData + uintptr(iPage)*4))
	return rc
}

// C documentation
//
//	/*
//	** Try to read the wal-index header.  Return 0 on success and 1 if
//	** there is a problem.
//	**
//	** The wal-index is in shared memory.  Another thread or process might
//	** be writing the header at the same time this procedure is trying to
//	** read it, which might result in inconsistency.  A dirty read is detected
//	** by verifying that both copies of the header are the same and also by
//	** a checksum on the header.
//	**
//	** If and only if the read is consistent and the header is different from
//	** pWal->hdr, then pWal->hdr is updated to the content of the new header
//	** and *pChanged is set to 1.
//	**
//	** If the checksum cannot be verified return non-zero. If the header
//	** is read successfully and the checksum verified, return zero.
//	*/
func _walIndexTryHdr(tls *libc.TLS, pWal uintptr, pChanged uintptr) (r int32) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var aHdr uintptr
	var _ /* aCksum at bp+0 */ [2]Tu32
	var _ /* h1 at bp+8 */ TWalIndexHdr
	var _ /* h2 at bp+56 */ TWalIndexHdr
	_ = aHdr /* Header in shared memory */
	/* The first page of the wal-index must be mapped at this point. */
	/* Read the header. This might happen concurrently with a write to the
	 ** same area of shared memory on a different CPU in a SMP,
	 ** meaning it is possible that an inconsistent snapshot is read
	 ** from the file. If this happens, return non-zero.
	 **
	 ** tag-20200519-1:
	 ** There are two copies of the header at the beginning of the wal-index.
	 ** When reading, read [0] first then [1].  Writes are in the reverse order.
	 ** Memory barriers are used to prevent the compiler or the hardware from
	 ** reordering the reads and writes.  TSAN and similar tools can sometimes
	 ** give false-positive warnings about these accesses because the tools do not
	 ** account for the double-read and the memory barrier. The use of mutexes
	 ** here would be problematic as the memory being accessed is potentially
	 ** shared among multiple processes and not all mutex implementations work
	 ** reliably in that environment.
	 */
	aHdr = _walIndexHdr(tls, pWal)
	libc.Xmemcpy(tls, bp+8, aHdr, uint32(48)) /* Possible TSAN false-positive */
	_walShmBarrier(tls, pWal)
	libc.Xmemcpy(tls, bp+56, aHdr+1*48, uint32(48))
	if libc.Xmemcmp(tls, bp+8, bp+56, uint32(48)) != 0 {
		return int32(1) /* Dirty read */
	}
	if libc.Int32FromUint8((**(**TWalIndexHdr)(__ccgo_up(bp + 8))).FisInit) == 0 {
		return int32(1) /* Malformed header - probably all zeros */
	}
	_walChecksumBytes(tls, int32(1), bp+8, libc.Int32FromUint32(libc.Uint32FromInt64(48)-libc.Uint32FromInt64(8)), uintptr(0), bp)
	if (**(**[2]Tu32)(__ccgo_up(bp)))[0] != **(**Tu32)(__ccgo_up(bp + 8 + 40)) || (**(**[2]Tu32)(__ccgo_up(bp)))[int32(1)] != **(**Tu32)(__ccgo_up(bp + 8 + 40 + 1*4)) {
		return int32(1) /* Checksum does not match */
	}
	if libc.Xmemcmp(tls, pWal+52, bp+8, uint32(48)) != 0 {
		**(**int32)(__ccgo_up(pChanged)) = int32(1)
		libc.Xmemcpy(tls, pWal+52, bp+8, uint32(48))
		(*TWal)(unsafe.Pointer(pWal)).FszPage = libc.Uint32FromInt32(libc.Int32FromUint16((*TWal)(unsafe.Pointer(pWal)).Fhdr.FszPage)&int32(0xfe00) + libc.Int32FromUint16((*TWal)(unsafe.Pointer(pWal)).Fhdr.FszPage)&int32(0x0001)<<int32(16))
	}
	/* The header was successfully read. Return zero. */
	return 0
}

/*
** This is the value that walTryBeginRead returns when it needs to
** be retried.
 */

// C documentation
//
//	/*
//	** Write the header information in pWal->hdr into the wal-index.
//	**
//	** The checksum on pWal->hdr is updated before it is written.
//	*/
func _walIndexWriteHdr(tls *libc.TLS, pWal uintptr) {
	var aHdr uintptr
	var nCksum int32
	_, _ = aHdr, nCksum
	aHdr = _walIndexHdr(tls, pWal)
	nCksum = libc.Int32FromUint32(uint32(libc.UintptrFromInt32(0) + 40))
	(*TWal)(unsafe.Pointer(pWal)).Fhdr.FisInit = uint8(1)
	(*TWal)(unsafe.Pointer(pWal)).Fhdr.FiVersion = uint32(WALINDEX_MAX_VERSION)
	_walChecksumBytes(tls, int32(1), pWal+52, nCksum, uintptr(0), pWal+52+40)
	/* Possible TSAN false-positive.  See tag-20200519-1 */
	libc.Xmemcpy(tls, aHdr+1*48, pWal+52, uint32(48))
	_walShmBarrier(tls, pWal)
	libc.Xmemcpy(tls, aHdr, pWal+52, uint32(48))
}

// C documentation
//
//	/*
//	** Construct a WalInterator object that can be used to loop over all
//	** pages in the WAL following frame nBackfill in ascending order. Frames
//	** nBackfill or earlier may be included - excluding them is an optimization
//	** only. The caller must hold the checkpoint lock.
//	**
//	** On success, make *pp point to the newly allocated WalInterator object
//	** return SQLITE_OK. Otherwise, return an error code. If this routine
//	** returns an error, the value of *pp is undefined.
//	**
//	** The calling routine should invoke walIteratorFree() to destroy the
//	** WalIterator object when it has finished with it.
//	*/
func _walIteratorInit(tls *libc.TLS, pWal uintptr, nBackfill Tu32, pp uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var aIndex, aTmp, p uintptr
	var i, j, nSegment, rc int32
	var iLast Tu32
	var nByte Tsqlite3_int64
	var v1 uint32
	var _ /* nEntry at bp+12 */ int32
	var _ /* sLoc at bp+0 */ TWalHashLoc
	_, _, _, _, _, _, _, _, _, _ = aIndex, aTmp, i, iLast, j, nByte, nSegment, p, rc, v1 /* Temp space used by merge-sort */
	rc = SQLITE_OK                                                                       /* Return Code */
	/* This routine only runs while holding the checkpoint lock. And
	 ** it only runs if there is actually content in the log (mxFrame>0).
	 */
	iLast = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame
	/* Allocate space for the WalIterator object. */
	nSegment = _walFramePage(tls, iLast) + int32(1)
	nByte = libc.Int64FromUint32(uint32(libc.UintptrFromInt32(0)+8) + libc.Uint32FromInt32(nSegment)*uint32(20) + iLast*uint32(2))
	if iLast > uint32(HASHTABLE_NPAGE) {
		v1 = uint32(HASHTABLE_NPAGE)
	} else {
		v1 = iLast
	}
	p = Xsqlite3_malloc64(tls, libc.Uint64FromInt64(nByte+libc.Int64FromUint32(uint32(2)*v1)))
	if !(p != 0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemset(tls, p, 0, libc.Uint32FromInt64(nByte))
	(*TWalIterator)(unsafe.Pointer(p)).FnSegment = nSegment
	aTmp = p + uintptr(nByte)
	i = _walFramePage(tls, nBackfill+uint32(1))
	for {
		if !(rc == SQLITE_OK && i < nSegment) {
			break
		}
		rc = _walHashGet(tls, pWal, i, bp)
		if rc == SQLITE_OK { /* Sorted index for this segment */
			if i+int32(1) == nSegment {
				**(**int32)(__ccgo_up(bp + 12)) = libc.Int32FromUint32(iLast - (**(**TWalHashLoc)(__ccgo_up(bp))).FiZero)
			} else {
				**(**int32)(__ccgo_up(bp + 12)) = (int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaHash) - int32((**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno)) / 4
			}
			aIndex = p + 8 + uintptr((*TWalIterator)(unsafe.Pointer(p)).FnSegment)*20 + uintptr((**(**TWalHashLoc)(__ccgo_up(bp))).FiZero)*2
			(**(**TWalHashLoc)(__ccgo_up(bp))).FiZero = (**(**TWalHashLoc)(__ccgo_up(bp))).FiZero + 1
			j = 0
			for {
				if !(j < **(**int32)(__ccgo_up(bp + 12))) {
					break
				}
				**(**Tht_slot)(__ccgo_up(aIndex + uintptr(j)*2)) = libc.Uint16FromInt32(j)
				goto _3
			_3:
				;
				j = j + 1
			}
			_walMergesort(tls, (**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno, aTmp, aIndex, bp+12)
			(*(*TWalSegment)(unsafe.Pointer(p + 8 + uintptr(i)*20))).FiZero = libc.Int32FromUint32((**(**TWalHashLoc)(__ccgo_up(bp))).FiZero)
			(*(*TWalSegment)(unsafe.Pointer(p + 8 + uintptr(i)*20))).FnEntry = **(**int32)(__ccgo_up(bp + 12))
			(*(*TWalSegment)(unsafe.Pointer(p + 8 + uintptr(i)*20))).FaIndex = aIndex
			(*(*TWalSegment)(unsafe.Pointer(p + 8 + uintptr(i)*20))).FaPgno = (**(**TWalHashLoc)(__ccgo_up(bp))).FaPgno
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	if rc != SQLITE_OK {
		_walIteratorFree(tls, p)
		p = uintptr(0)
	}
	**(**uintptr)(__ccgo_up(pp)) = p
	return rc
}

// C documentation
//
//	/*
//	** Find the smallest page number out of all pages held in the WAL that
//	** has not been returned by any prior invocation of this method on the
//	** same WalIterator object.   Write into *piFrame the frame index where
//	** that page was last written into the WAL.  Write into *piPage the page
//	** number.
//	**
//	** Return 0 on success.  If there are no pages in the WAL with a page
//	** number larger than *piPage, then return 1.
//	*/
func _walIteratorNext(tls *libc.TLS, p uintptr, piPage uintptr, piFrame uintptr) (r int32) {
	var i int32
	var iMin, iPg, iRet, v2 Tu32
	var pSegment uintptr
	_, _, _, _, _, _ = i, iMin, iPg, iRet, pSegment, v2 /* Result pgno must be greater than iMin */
	iRet = uint32(0xFFFFFFFF)                           /* For looping through segments */
	iMin = (*TWalIterator)(unsafe.Pointer(p)).FiPrior
	i = (*TWalIterator)(unsafe.Pointer(p)).FnSegment - int32(1)
	for {
		if !(i >= 0) {
			break
		}
		pSegment = p + 8 + uintptr(i)*20
		for (*TWalSegment)(unsafe.Pointer(pSegment)).FiNext < (*TWalSegment)(unsafe.Pointer(pSegment)).FnEntry {
			iPg = **(**Tu32)(__ccgo_up((*TWalSegment)(unsafe.Pointer(pSegment)).FaPgno + uintptr(**(**Tht_slot)(__ccgo_up((*TWalSegment)(unsafe.Pointer(pSegment)).FaIndex + uintptr((*TWalSegment)(unsafe.Pointer(pSegment)).FiNext)*2)))*4))
			if iPg > iMin {
				if iPg < iRet {
					iRet = iPg
					**(**Tu32)(__ccgo_up(piFrame)) = libc.Uint32FromInt32((*TWalSegment)(unsafe.Pointer(pSegment)).FiZero + libc.Int32FromUint16(**(**Tht_slot)(__ccgo_up((*TWalSegment)(unsafe.Pointer(pSegment)).FaIndex + uintptr((*TWalSegment)(unsafe.Pointer(pSegment)).FiNext)*2))))
				}
				break
			}
			(*TWalSegment)(unsafe.Pointer(pSegment)).FiNext = (*TWalSegment)(unsafe.Pointer(pSegment)).FiNext + 1
		}
		goto _1
	_1:
		;
		i = i - 1
	}
	v2 = iRet
	(*TWalIterator)(unsafe.Pointer(p)).FiPrior = v2
	**(**Tu32)(__ccgo_up(piPage)) = v2
	return libc.BoolInt32(iRet == uint32(0xFFFFFFFF))
}

// C documentation
//
//	/*
//	** This function merges two sorted lists into a single sorted list.
//	**
//	** aLeft[] and aRight[] are arrays of indices.  The sort key is
//	** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
//	** is guaranteed for all J<K:
//	**
//	**        aContent[aLeft[J]] < aContent[aLeft[K]]
//	**        aContent[aRight[J]] < aContent[aRight[K]]
//	**
//	** This routine overwrites aRight[] with a new (probably longer) sequence
//	** of indices such that the aRight[] contains every index that appears in
//	** either aLeft[] or the old aRight[] and such that the second condition
//	** above is still met.
//	**
//	** The aContent[aLeft[X]] values will be unique for all X.  And the
//	** aContent[aRight[X]] values will be unique too.  But there might be
//	** one or more combinations of X and Y such that
//	**
//	**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
//	**
//	** When that happens, omit the aLeft[X] and use the aRight[Y] index.
//	*/
func _walMerge(tls *libc.TLS, aContent uintptr, aLeft uintptr, nLeft int32, paRight uintptr, pnRight uintptr, aTmp uintptr) {
	var aRight uintptr
	var dbpage TPgno
	var iLeft, iOut, iRight, nRight, v1 int32
	var logpage Tht_slot
	_, _, _, _, _, _, _, _ = aRight, dbpage, iLeft, iOut, iRight, logpage, nRight, v1
	iLeft = 0  /* Current index in aLeft */
	iRight = 0 /* Current index in aRight */
	iOut = 0   /* Current index in output buffer */
	nRight = **(**int32)(__ccgo_up(pnRight))
	aRight = **(**uintptr)(__ccgo_up(paRight))
	for iRight < nRight || iLeft < nLeft {
		if iLeft < nLeft && (iRight >= nRight || **(**Tu32)(__ccgo_up(aContent + uintptr(**(**Tht_slot)(__ccgo_up(aLeft + uintptr(iLeft)*2)))*4)) < **(**Tu32)(__ccgo_up(aContent + uintptr(**(**Tht_slot)(__ccgo_up(aRight + uintptr(iRight)*2)))*4))) {
			v1 = iLeft
			iLeft = iLeft + 1
			logpage = **(**Tht_slot)(__ccgo_up(aLeft + uintptr(v1)*2))
		} else {
			v1 = iRight
			iRight = iRight + 1
			logpage = **(**Tht_slot)(__ccgo_up(aRight + uintptr(v1)*2))
		}
		dbpage = **(**Tu32)(__ccgo_up(aContent + uintptr(logpage)*4))
		v1 = iOut
		iOut = iOut + 1
		**(**Tht_slot)(__ccgo_up(aTmp + uintptr(v1)*2)) = logpage
		if iLeft < nLeft && **(**Tu32)(__ccgo_up(aContent + uintptr(**(**Tht_slot)(__ccgo_up(aLeft + uintptr(iLeft)*2)))*4)) == dbpage {
			iLeft = iLeft + 1
		}
	}
	**(**uintptr)(__ccgo_up(paRight)) = aLeft
	**(**int32)(__ccgo_up(pnRight)) = iOut
	libc.Xmemcpy(tls, aLeft, aTmp, uint32(2)*libc.Uint32FromInt32(iOut))
}

// C documentation
//
//	/*
//	** Sort the elements in list aList using aContent[] as the sort key.
//	** Remove elements with duplicate keys, preferring to keep the
//	** larger aList[] values.
//	**
//	** The aList[] entries are indices into aContent[].  The values in
//	** aList[] are to be sorted so that for all J<K:
//	**
//	**      aContent[aList[J]] < aContent[aList[K]]
//	**
//	** For any X and Y such that
//	**
//	**      aContent[aList[X]] == aContent[aList[Y]]
//	**
//	** Keep the larger of the two values aList[X] and aList[Y] and discard
//	** the smaller.
//	*/
func _walMergesort(tls *libc.TLS, aContent uintptr, aBuffer uintptr, aList uintptr, pnList uintptr) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var iList, nList int32
	var iSub Tu32
	var p, p1 uintptr
	var _ /* aMerge at bp+4 */ uintptr
	var _ /* aSub at bp+8 */ [13]struct {
		FnList int32
		FaList uintptr
	}
	var _ /* nMerge at bp+0 */ int32
	_, _, _, _, _ = iList, iSub, nList, p, p1
	nList = **(**int32)(__ccgo_up(pnList))        /* Size of input list */
	**(**int32)(__ccgo_up(bp)) = 0                /* Number of elements in list aMerge */
	**(**uintptr)(__ccgo_up(bp + 4)) = uintptr(0) /* Index into input list */
	iSub = uint32(0)                              /* Array of sub-lists */
	libc.Xmemset(tls, bp+8, 0, uint32(104))
	iList = 0
	for {
		if !(iList < nList) {
			break
		}
		**(**int32)(__ccgo_up(bp)) = int32(1)
		**(**uintptr)(__ccgo_up(bp + 4)) = aList + uintptr(iList)*2
		iSub = uint32(0)
		for {
			if !(iList&(int32(1)<<iSub) != 0) {
				break
			}
			p = bp + 8 + uintptr(iSub)*8
			_walMerge(tls, aContent, (*struct {
				FnList int32
				FaList uintptr
			})(unsafe.Pointer(p)).FaList, (*struct {
				FnList int32
				FaList uintptr
			})(unsafe.Pointer(p)).FnList, bp+4, bp, aBuffer)
			goto _2
		_2:
			;
			iSub = iSub + 1
		}
		(**(**[13]struct {
			FnList int32
			FaList uintptr
		})(__ccgo_up(bp + 8)))[iSub].FaList = **(**uintptr)(__ccgo_up(bp + 4))
		(**(**[13]struct {
			FnList int32
			FaList uintptr
		})(__ccgo_up(bp + 8)))[iSub].FnList = **(**int32)(__ccgo_up(bp))
		goto _1
	_1:
		;
		iList = iList + 1
	}
	iSub = iSub + 1
	for {
		if !(iSub < libc.Uint32FromInt32(libc.Int32FromUint32(libc.Uint32FromInt64(104)/libc.Uint32FromInt64(8)))) {
			break
		}
		if nList&(int32(1)<<iSub) != 0 {
			p1 = bp + 8 + uintptr(iSub)*8
			_walMerge(tls, aContent, (*struct {
				FnList int32
				FaList uintptr
			})(unsafe.Pointer(p1)).FaList, (*struct {
				FnList int32
				FaList uintptr
			})(unsafe.Pointer(p1)).FnList, bp+4, bp, aBuffer)
		}
		goto _3
	_3:
		;
		iSub = iSub + 1
	}
	**(**int32)(__ccgo_up(pnList)) = **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/*
//	** The following is guaranteed when this function is called:
//	**
//	**   a) the WRITER lock is held,
//	**   b) the entire log file has been checkpointed, and
//	**   c) any existing readers are reading exclusively from the database
//	**      file - there are no readers that may attempt to read a frame from
//	**      the log file.
//	**
//	** This function updates the shared-memory structures so that the next
//	** client to write to the database (which may be this one) does so by
//	** writing frames into the start of the log file.
//	**
//	** The value of parameter salt1 is used as the aSalt[1] value in the
//	** new wal-index header. It should be passed a pseudo-random value (i.e.
//	** one obtained from sqlite3_randomness()).
//	*/
func _walRestartHdr(tls *libc.TLS, pWal uintptr, _salt1 Tu32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	*(*Tu32)(unsafe.Pointer(bp)) = _salt1
	var aSalt, pInfo uintptr
	var i int32
	_, _, _ = aSalt, i, pInfo
	pInfo = _walCkptInfo(tls, pWal) /* Loop counter */
	aSalt = pWal + 52 + 32          /* Big-endian salt values */
	(*TWal)(unsafe.Pointer(pWal)).FnCkpt = (*TWal)(unsafe.Pointer(pWal)).FnCkpt + 1
	(*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame = uint32(0)
	_sqlite3Put4byte(tls, aSalt, uint32(1)+_sqlite3Get4byte(tls, aSalt))
	libc.Xmemcpy(tls, pWal+52+32+1*4, bp, uint32(4))
	_walIndexWriteHdr(tls, pWal)
	libc.AtomicStoreNUint32(pInfo, libc.Uint32FromInt32(libc.Int32FromInt32(0)), libc.Int32FromInt32(__ATOMIC_RELAXED))
	(*TWalCkptInfo)(unsafe.Pointer(pInfo)).FnBackfillAttempted = uint32(0)
	**(**Tu32)(__ccgo_up(pInfo + 4 + 1*4)) = uint32(0)
	i = int32(2)
	for {
		if !(i < libc.Int32FromInt32(SQLITE_SHM_NLOCK)-libc.Int32FromInt32(3)) {
			break
		}
		**(**Tu32)(__ccgo_up(pInfo + 4 + uintptr(i)*4)) = uint32(READMARK_NOT_USED)
		goto _1
	_1:
		;
		i = i + 1
	}
}

// C documentation
//
//	/*
//	** This function is called as part of committing a transaction within which
//	** one or more frames have been overwritten. It updates the checksums for
//	** all frames written to the wal file by the current transaction starting
//	** with the earliest to have been overwritten.
//	**
//	** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
//	*/
func _walRewriteChecksums(tls *libc.TLS, pWal uintptr, iLast Tu32) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var aBuf uintptr
	var iCksumOff, iOff Ti64
	var iPgno, iRead, nDbSize Tu32
	var rc, szPage int32
	var _ /* aFrame at bp+0 */ [24]Tu8
	_, _, _, _, _, _, _, _ = aBuf, iCksumOff, iOff, iPgno, iRead, nDbSize, rc, szPage
	szPage = libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage) /* Database page size */
	rc = SQLITE_OK
	aBuf = Xsqlite3_malloc(tls, szPage+int32(WAL_FRAME_HDRSIZE))
	if aBuf == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	/* Find the checksum values to use as input for the recalculating the
	 ** first checksum. If the first frame is frame 1 (implying that the current
	 ** transaction restarted the wal file), these values must be read from the
	 ** wal-file header. Otherwise, read them from the frame header of the
	 ** previous frame.  */
	if (*TWal)(unsafe.Pointer(pWal)).FiReCksum == uint32(1) {
		iCksumOff = int64(24)
	} else {
		iCksumOff = int64(WAL_HDRSIZE) + libc.Int64FromUint32((*TWal)(unsafe.Pointer(pWal)).FiReCksum-libc.Uint32FromInt32(1)-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE)) + int64(16)
	}
	rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, aBuf, libc.Int32FromUint32(libc.Uint32FromInt64(4)*libc.Uint32FromInt32(2)), iCksumOff)
	**(**Tu32)(__ccgo_up(pWal + 52 + 24)) = _sqlite3Get4byte(tls, aBuf)
	**(**Tu32)(__ccgo_up(pWal + 52 + 24 + 1*4)) = _sqlite3Get4byte(tls, aBuf+uintptr(4))
	iRead = (*TWal)(unsafe.Pointer(pWal)).FiReCksum
	(*TWal)(unsafe.Pointer(pWal)).FiReCksum = uint32(0)
	for {
		if !(rc == SQLITE_OK && iRead <= iLast) {
			break
		}
		iOff = libc.Int64FromInt32(WAL_HDRSIZE) + libc.Int64FromUint32(iRead-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE))
		rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, aBuf, szPage+int32(WAL_FRAME_HDRSIZE), iOff)
		if rc == SQLITE_OK {
			iPgno = _sqlite3Get4byte(tls, aBuf)
			nDbSize = _sqlite3Get4byte(tls, aBuf+4)
			_walEncodeFrame(tls, pWal, iPgno, nDbSize, aBuf+24, bp)
			rc = _sqlite3OsWrite(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, bp, int32(24), iOff)
		}
		goto _1
	_1:
		;
		iRead = iRead + 1
	}
	Xsqlite3_free(tls, aBuf)
	return rc
}

// C documentation
//
//	/*
//	** This function does the work of sqlite3WalSnapshotRecover().
//	*/
func _walSnapshotRecover(tls *libc.TLS, pWal uintptr, pBuf1 uintptr, pBuf2 uintptr) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var i, pgno Tu32
	var iDbOff, iWalOff Ti64
	var pInfo uintptr
	var rc, szPage int32
	var _ /* sLoc at bp+8 */ TWalHashLoc
	var _ /* szDb at bp+0 */ Ti64
	_, _, _, _, _, _, _ = i, iDbOff, iWalOff, pInfo, pgno, rc, szPage
	szPage = libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage) /* Size of db file in bytes */
	rc = _sqlite3OsFileSize(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, bp)
	if rc == SQLITE_OK {
		pInfo = _walCkptInfo(tls, pWal)
		i = (*TWalCkptInfo)(unsafe.Pointer(pInfo)).FnBackfillAttempted
		i = (*TWalCkptInfo)(unsafe.Pointer(pInfo)).FnBackfillAttempted
		for {
			if !(i > libc.AtomicLoadNUint32(pInfo, libc.Int32FromInt32(__ATOMIC_RELAXED))) {
				break
			} /* Offset of wal file entry */
			rc = _walHashGet(tls, pWal, _walFramePage(tls, i), bp+8)
			if rc != SQLITE_OK {
				break
			}
			pgno = **(**Tu32)(__ccgo_up((**(**TWalHashLoc)(__ccgo_up(bp + 8))).FaPgno + uintptr(i-(**(**TWalHashLoc)(__ccgo_up(bp + 8))).FiZero-uint32(1))*4))
			iDbOff = libc.Int64FromUint32(pgno-libc.Uint32FromInt32(1)) * int64(szPage)
			if iDbOff+int64(szPage) <= **(**Ti64)(__ccgo_up(bp)) {
				iWalOff = int64(WAL_HDRSIZE) + libc.Int64FromUint32(i-libc.Uint32FromInt32(1))*int64(szPage+libc.Int32FromInt32(WAL_FRAME_HDRSIZE)) + int64(WAL_FRAME_HDRSIZE)
				rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpWalFd, pBuf1, szPage, iWalOff)
				if rc == SQLITE_OK {
					rc = _sqlite3OsRead(tls, (*TWal)(unsafe.Pointer(pWal)).FpDbFd, pBuf2, szPage, iDbOff)
				}
				if rc != SQLITE_OK || 0 == libc.Xmemcmp(tls, pBuf1, pBuf2, libc.Uint32FromInt32(szPage)) {
					break
				}
			}
			(*TWalCkptInfo)(unsafe.Pointer(pInfo)).FnBackfillAttempted = i - uint32(1)
			goto _1
		_1:
			;
			i = i - 1
		}
	}
	return rc
}

// C documentation
//
//	/*
//	** Attempt to start a read transaction.  This might fail due to a race or
//	** other transient condition.  When that happens, it returns WAL_RETRY to
//	** indicate to the caller that it is safe to retry immediately.
//	**
//	** On success return SQLITE_OK.  On a permanent failure (such an
//	** I/O error or an SQLITE_BUSY because another process is running
//	** recovery) return a positive error code.
//	**
//	** The useWal parameter is true to force the use of the WAL and disable
//	** the case where the WAL is bypassed because it has been completely
//	** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
//	** to make a copy of the wal-index header into pWal->hdr.  If the
//	** wal-index header has changed, *pChanged is set to 1 (as an indication
//	** to the caller that the local page cache is obsolete and needs to be
//	** flushed.)  When useWal==1, the wal-index header is assumed to already
//	** be loaded and the pChanged parameter is unused.
//	**
//	** The caller must set the cnt parameter to the number of prior calls to
//	** this routine during the current read attempt that returned WAL_RETRY.
//	** This routine will start taking more aggressive measures to clear the
//	** race conditions after multiple WAL_RETRY returns, and after an excessive
//	** number of errors will ultimately return SQLITE_PROTOCOL.  The
//	** SQLITE_PROTOCOL return indicates that some other process has gone rogue
//	** and is not honoring the locking protocol.  There is a vanishingly small
//	** chance that SQLITE_PROTOCOL could be returned because of a run of really
//	** bad luck when there is lots of contention for the wal-index, but that
//	** possibility is so small that it can be safely neglected, we believe.
//	**
//	** On success, this routine obtains a read lock on
//	** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
//	** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
//	** that means the Wal does not hold any read lock.  The reader must not
//	** access any database page that is modified by a WAL frame up to and
//	** including frame number aReadMark[pWal->readLock].  The reader will
//	** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
//	** Or if pWal->readLock==0, then the reader will ignore the WAL
//	** completely and get all content directly from the database file.
//	** If the useWal parameter is 1 then the WAL will never be ignored and
//	** this routine will always set pWal->readLock>0 on success.
//	** When the read transaction is completed, the caller must release the
//	** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
//	**
//	** This routine uses the nBackfill and aReadMark[] fields of the header
//	** to select a particular WAL_READ_LOCK() that strives to let the
//	** checkpoint process do as much work as possible.  This routine might
//	** update values of the aReadMark[] array in the header, but if it does
//	** so it takes care to hold an exclusive lock on the corresponding
//	** WAL_READ_LOCK() while changing values.
//	*/
func _walTryBeginRead(tls *libc.TLS, pWal uintptr, pChanged uintptr, useWal int32, pCnt uintptr) (r int32) {
	var cnt, i, mxI, nDelay, rc, v1 int32
	var mxFrame, mxReadMark, thisMark Tu32
	var pInfo uintptr
	_, _, _, _, _, _, _, _, _, _ = cnt, i, mxFrame, mxI, mxReadMark, nDelay, pInfo, rc, thisMark, v1 /* Checkpoint information in wal-index */
	rc = SQLITE_OK                                                                                   /* Return code  */
	/* Not currently locked */
	/* useWal may only be set for read/write connections */
	/* Take steps to avoid spinning forever if there is a protocol error.
	 **
	 ** Circumstances that cause a RETRY should only last for the briefest
	 ** instances of time.  No I/O or other system calls are done while the
	 ** locks are held, so the locks should not be held for very long. But
	 ** if we are unlucky, another process that is holding a lock might get
	 ** paged out or take a page-fault that is time-consuming to resolve,
	 ** during the few nanoseconds that it is holding the lock.  In that case,
	 ** it might take longer than normal for the lock to free.
	 **
	 ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
	 ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
	 ** is more of a scheduler yield than an actual delay.  But on the 10th
	 ** an subsequent retries, the delays start becoming longer and longer,
	 ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
	 ** The total delay time before giving up is less than 10 seconds.
	 */
	**(**int32)(__ccgo_up(pCnt)) = **(**int32)(__ccgo_up(pCnt)) + 1
	if **(**int32)(__ccgo_up(pCnt)) > int32(5) {
		nDelay = int32(1) /* Pause time in microseconds */
		cnt = **(**int32)(__ccgo_up(pCnt)) & ^libc.Int32FromInt32(WAL_RETRY_BLOCKED_MASK)
		if cnt > int32(WAL_RETRY_PROTOCOL_LIMIT) {
			return int32(SQLITE_PROTOCOL)
		}
		if **(**int32)(__ccgo_up(pCnt)) >= int32(10) {
			nDelay = (cnt - int32(9)) * (cnt - int32(9)) * int32(39)
		}
		_sqlite3OsSleep(tls, (*TWal)(unsafe.Pointer(pWal)).FpVfs, nDelay)
		**(**int32)(__ccgo_up(pCnt)) &= ^libc.Int32FromInt32(WAL_RETRY_BLOCKED_MASK)
	}
	if !(useWal != 0) {
		if libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FbShmUnreliable) == 0 {
			rc = _walIndexReadHdr(tls, pWal, pChanged)
		}
		if rc == int32(SQLITE_BUSY) {
			/* If there is not a recovery running in another thread or process
			 ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
			 ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
			 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
			 ** would be technically correct.  But the race is benign since with
			 ** WAL_RETRY this routine will be called again and will probably be
			 ** right on the second iteration.
			 */
			if **(**uintptr)(__ccgo_up((*TWal)(unsafe.Pointer(pWal)).FapWiData)) == uintptr(0) {
				/* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
				 ** We assume this is a transient condition, so return WAL_RETRY. The
				 ** xShmMap() implementation used by the default unix and win32 VFS
				 ** modules may return SQLITE_BUSY due to a race condition in the
				 ** code that determines whether or not the shared-memory region
				 ** must be zeroed before the requested page is returned.
				 */
				rc = -int32(1)
			} else {
				v1 = _walLockShared(tls, pWal, int32(WAL_RECOVER_LOCK))
				rc = v1
				if SQLITE_OK == v1 {
					_walUnlockShared(tls, pWal, int32(WAL_RECOVER_LOCK))
					rc = -int32(1)
				} else {
					if rc == int32(SQLITE_BUSY) {
						rc = libc.Int32FromInt32(SQLITE_BUSY) | libc.Int32FromInt32(1)<<libc.Int32FromInt32(8)
					}
				}
			}
		}
		if rc != SQLITE_OK {
			return rc
		} else {
			if (*TWal)(unsafe.Pointer(pWal)).FbShmUnreliable != 0 {
				return _walBeginShmUnreliable(tls, pWal, pChanged)
			}
		}
	}
	pInfo = _walCkptInfo(tls, pWal)
	/* Wal frame to lock to */
	if !(useWal != 0) && libc.AtomicLoadNUint32(pInfo, libc.Int32FromInt32(__ATOMIC_RELAXED)) == (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame && ((*TWal)(unsafe.Pointer(pWal)).FbGetSnapshot == 0 && (*TWal)(unsafe.Pointer(pWal)).FpSnapshot == uintptr(0) || (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame == uint32(0)) {
		/* The WAL has been completely backfilled (or it is empty).
		 ** and can be safely ignored.
		 */
		rc = _walLockShared(tls, pWal, libc.Int32FromInt32(3)+libc.Int32FromInt32(0))
		_walShmBarrier(tls, pWal)
		if rc == SQLITE_OK {
			if libc.Xmemcmp(tls, _walIndexHdr(tls, pWal), pWal+52, uint32(48)) != 0 {
				/* It is not safe to allow the reader to continue here if frames
				 ** may have been appended to the log before READ_LOCK(0) was obtained.
				 ** When holding READ_LOCK(0), the reader ignores the entire log file,
				 ** which implies that the database file contains a trustworthy
				 ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
				 ** happening, this is usually correct.
				 **
				 ** However, if frames have been appended to the log (or if the log
				 ** is wrapped and written for that matter) before the READ_LOCK(0)
				 ** is obtained, that is not necessarily true. A checkpointer may
				 ** have started to backfill the appended frames but crashed before
				 ** it finished. Leaving a corrupt image in the database file.
				 */
				_walUnlockShared(tls, pWal, libc.Int32FromInt32(3)+libc.Int32FromInt32(0))
				return -int32(1)
			}
			(*TWal)(unsafe.Pointer(pWal)).FreadLock = 0
			return SQLITE_OK
		} else {
			if rc != int32(SQLITE_BUSY) {
				return rc
			}
		}
	}
	/* If we get this far, it means that the reader will want to use
	 ** the WAL to get at content from recent commits.  The job now is
	 ** to select one of the aReadMark[] entries that is closest to
	 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
	 */
	mxReadMark = uint32(0)
	mxI = 0
	mxFrame = (*TWal)(unsafe.Pointer(pWal)).Fhdr.FmxFrame
	if (*TWal)(unsafe.Pointer(pWal)).FpSnapshot != 0 && (*TWalIndexHdr)(unsafe.Pointer((*TWal)(unsafe.Pointer(pWal)).FpSnapshot)).FmxFrame < mxFrame {
		mxFrame = (*TWalIndexHdr)(unsafe.Pointer((*TWal)(unsafe.Pointer(pWal)).FpSnapshot)).FmxFrame
	}
	i = int32(1)
	for {
		if !(i < libc.Int32FromInt32(SQLITE_SHM_NLOCK)-libc.Int32FromInt32(3)) {
			break
		}
		thisMark = libc.AtomicLoadNUint32(pInfo+4+uintptr(i)*4, libc.Int32FromInt32(__ATOMIC_RELAXED))
		if mxReadMark <= thisMark && thisMark <= mxFrame {
			mxReadMark = thisMark
			mxI = i
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	if libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).FreadOnly)&int32(WAL_SHM_RDONLY) == 0 && (mxReadMark < mxFrame || mxI == 0) {
		i = int32(1)
		for {
			if !(i < libc.Int32FromInt32(SQLITE_SHM_NLOCK)-libc.Int32FromInt32(3)) {
				break
			}
			rc = _walLockExclusive(tls, pWal, int32(3)+i, int32(1))
			if rc == SQLITE_OK {
				libc.AtomicStoreNUint32(pInfo+4+uintptr(i)*4, mxFrame, libc.Int32FromInt32(__ATOMIC_RELAXED))
				mxReadMark = mxFrame
				mxI = i
				_walUnlockExclusive(tls, pWal, int32(3)+i, int32(1))
				break
			} else {
				if rc != int32(SQLITE_BUSY) {
					return rc
				}
			}
			goto _3
		_3:
			;
			i = i + 1
		}
	}
	if mxI == 0 {
		if rc == int32(SQLITE_BUSY) {
			v1 = -int32(1)
		} else {
			v1 = libc.Int32FromInt32(SQLITE_READONLY) | libc.Int32FromInt32(5)<<libc.Int32FromInt32(8)
		}
		return v1
	}
	rc = _walLockShared(tls, pWal, int32(3)+mxI)
	if rc != 0 {
		if rc&int32(0xFF) == int32(SQLITE_BUSY) {
			v1 = -int32(1)
		} else {
			v1 = rc
		}
		return v1
	}
	/* Now that the read-lock has been obtained, check that neither the
	 ** value in the aReadMark[] array or the contents of the wal-index
	 ** header have changed.
	 **
	 ** It is necessary to check that the wal-index header did not change
	 ** between the time it was read and when the shared-lock was obtained
	 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
	 ** that the log file may have been wrapped by a writer, or that frames
	 ** that occur later in the log than pWal->hdr.mxFrame may have been
	 ** copied into the database by a checkpointer. If either of these things
	 ** happened, then reading the database with the current value of
	 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
	 ** instead.
	 **
	 ** Before checking that the live wal-index header has not changed
	 ** since it was read, set Wal.minFrame to the first frame in the wal
	 ** file that has not yet been checkpointed. This client will not need
	 ** to read any frames earlier than minFrame from the wal file - they
	 ** can be safely read directly from the database file.
	 **
	 ** Because a ShmBarrier() call is made between taking the copy of
	 ** nBackfill and checking that the wal-header in shared-memory still
	 ** matches the one cached in pWal->hdr, it is guaranteed that the
	 ** checkpointer that set nBackfill was not working with a wal-index
	 ** header newer than that cached in pWal->hdr. If it were, that could
	 ** cause a problem. The checkpointer could omit to checkpoint
	 ** a version of page X that lies before pWal->minFrame (call that version
	 ** A) on the basis that there is a newer version (version B) of the same
	 ** page later in the wal file. But if version B happens to like past
	 ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
	 ** that it can read version A from the database file. However, since
	 ** we can guarantee that the checkpointer that set nBackfill could not
	 ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
	 */
	(*TWal)(unsafe.Pointer(pWal)).FminFrame = libc.Uint32FromInt32(libc.Int32FromUint32(libc.AtomicLoadNUint32(pInfo, libc.Int32FromInt32(__ATOMIC_RELAXED))) + int32(1))
	_walShmBarrier(tls, pWal)
	if libc.AtomicLoadNUint32(pInfo+4+uintptr(mxI)*4, libc.Int32FromInt32(__ATOMIC_RELAXED)) != mxReadMark || libc.Xmemcmp(tls, _walIndexHdr(tls, pWal), pWal+52, uint32(48)) != 0 {
		_walUnlockShared(tls, pWal, int32(3)+mxI)
		return -int32(1)
	} else {
		(*TWal)(unsafe.Pointer(pWal)).FreadLock = int16(mxI)
	}
	return rc
}

// C documentation
//
//	/*
//	** Write out a single frame of the WAL
//	*/
func _walWriteOneFrame(tls *libc.TLS, p uintptr, pPage uintptr, nTruncate int32, iOffset Tsqlite3_int64) (r int32) {
	bp := tls.Alloc(32)
	defer tls.Free(32)
	var pData uintptr
	var rc int32
	var _ /* aFrame at bp+0 */ [24]Tu8
	_, _ = pData, rc /* Buffer to assemble frame-header in */
	pData = (*TPgHdr)(unsafe.Pointer(pPage)).FpData
	_walEncodeFrame(tls, (*TWalWriter)(unsafe.Pointer(p)).FpWal, (*TPgHdr)(unsafe.Pointer(pPage)).Fpgno, libc.Uint32FromInt32(nTruncate), pData, bp)
	rc = _walWriteToLog(tls, p, bp, int32(24), iOffset)
	if rc != 0 {
		return rc
	}
	/* Write the page data */
	rc = _walWriteToLog(tls, p, pData, (*TWalWriter)(unsafe.Pointer(p)).FszPage, iOffset+int64(24))
	return rc
}

// C documentation
//
//	/*
//	** Add either a LIMIT (if eMatchOp==SQLITE_INDEX_CONSTRAINT_LIMIT) or
//	** OFFSET (if eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET) term to the
//	** where-clause passed as the first argument. The value for the term
//	** is found in register iReg.
//	**
//	** In the common case where the value is a simple integer
//	** (example: "LIMIT 5 OFFSET 10") then the expression codes as a
//	** TK_INTEGER so that it will be available to sqlite3_vtab_rhs_value().
//	** If not, then it codes as a TK_REGISTER expression.
//	*/
func _whereAddLimitExpr(tls *libc.TLS, pWC uintptr, iReg int32, pExpr uintptr, iCsr int32, eMatchOp int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var db, pNew, pParse, pTerm, pVal, pVal1 uintptr
	var idx int32
	var _ /* iVal at bp+0 */ int32
	_, _, _, _, _, _, _ = db, idx, pNew, pParse, pTerm, pVal, pVal1
	pParse = (*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpParse
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb
	**(**int32)(__ccgo_up(bp)) = 0
	if _sqlite3ExprIsInteger(tls, pExpr, bp, pParse) != 0 && **(**int32)(__ccgo_up(bp)) >= 0 {
		pVal = _sqlite3ExprInt32(tls, db, **(**int32)(__ccgo_up(bp)))
		if pVal == uintptr(0) {
			return
		}
		pNew = _sqlite3PExpr(tls, pParse, int32(TK_MATCH), uintptr(0), pVal)
	} else {
		pVal1 = _sqlite3ExprAlloc(tls, db, int32(TK_REGISTER), uintptr(0), 0)
		if pVal1 == uintptr(0) {
			return
		}
		(*TExpr)(unsafe.Pointer(pVal1)).FiTable = iReg
		pNew = _sqlite3PExpr(tls, pParse, int32(TK_MATCH), uintptr(0), pVal1)
	}
	if pNew != 0 {
		idx = _whereClauseInsert(tls, pWC, pNew, libc.Uint16FromInt32(libc.Int32FromInt32(TERM_DYNAMIC)|libc.Int32FromInt32(TERM_VIRTUAL)))
		pTerm = (*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(idx)*48
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FleftCursor = iCsr
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator = uint16(WO_AUX)
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FeMatchOp = libc.Uint8FromInt32(eMatchOp)
	}
}

// C documentation
//
//	/*
//	** The pTruth expression is always true because it is the WHERE clause
//	** a partial index that is driving a query loop.  Look through all of the
//	** WHERE clause terms on the query, and if any of those terms must be
//	** true because pTruth is true, then mark those WHERE clause terms as
//	** coded.
//	*/
func _whereApplyPartialIndexConstraints(tls *libc.TLS, pTruth uintptr, iTabCur int32, pWC uintptr) {
	var i int32
	var pExpr, pTerm, v2 uintptr
	_, _, _, _ = i, pExpr, pTerm, v2
	for libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pTruth)).Fop) == int32(TK_AND) {
		_whereApplyPartialIndexConstraints(tls, (*TExpr)(unsafe.Pointer(pTruth)).FpLeft, iTabCur, pWC)
		pTruth = (*TExpr)(unsafe.Pointer(pTruth)).FpRight
	}
	i = 0
	pTerm = (*TWhereClause)(unsafe.Pointer(pWC)).Fa
	for {
		if !(i < (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm) {
			break
		}
		if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_CODED) != 0 {
			goto _1
		}
		pExpr = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
		if _sqlite3ExprCompare(tls, uintptr(0), pExpr, pTruth, iTabCur) == 0 {
			v2 = pTerm + 10
			*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(TERM_CODED))
		}
		goto _1
	_1:
		;
		i = i + 1
		pTerm += 48
	}
}

// C documentation
//
//	/*
//	** Add a single new WhereTerm entry to the WhereClause object pWC.
//	** The new WhereTerm object is constructed from Expr p and with wtFlags.
//	** The index in pWC->a[] of the new WhereTerm is returned on success.
//	** 0 is returned if the new WhereTerm could not be added due to a memory
//	** allocation error.  The memory allocation failure will be recorded in
//	** the db->mallocFailed flag so that higher-level functions can detect it.
//	**
//	** This routine will increase the size of the pWC->a[] array as necessary.
//	**
//	** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
//	** for freeing the expression p is assumed by the WhereClause object pWC.
//	** This is true even if this routine fails to allocate a new WhereTerm.
//	**
//	** WARNING:  This routine might reallocate the space used to store
//	** WhereTerms.  All pointers to WhereTerms should be invalidated after
//	** calling this routine.  Such pointers may be reinitialized by referencing
//	** the pWC->a[] array.
//	*/
func _whereClauseInsert(tls *libc.TLS, pWC uintptr, p uintptr, wtFlags Tu16) (r int32) {
	var db, pOld, pTerm, v3 uintptr
	var idx, v1, v2 int32
	_, _, _, _, _, _, _ = db, idx, pOld, pTerm, v1, v2, v3
	if (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm >= (*TWhereClause)(unsafe.Pointer(pWC)).FnSlot {
		pOld = (*TWhereClause)(unsafe.Pointer(pWC)).Fa
		db = (*TParse)(unsafe.Pointer((*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpParse)).Fdb
		(*TWhereClause)(unsafe.Pointer(pWC)).Fa = _sqlite3WhereMalloc(tls, (*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo, uint64(uint32(48)*libc.Uint32FromInt32((*TWhereClause)(unsafe.Pointer(pWC)).FnSlot)*uint32(2)))
		if (*TWhereClause)(unsafe.Pointer(pWC)).Fa == uintptr(0) {
			if libc.Int32FromUint16(wtFlags)&int32(TERM_DYNAMIC) != 0 {
				_sqlite3ExprDelete(tls, db, p)
			}
			(*TWhereClause)(unsafe.Pointer(pWC)).Fa = pOld
			return 0
		}
		libc.Xmemcpy(tls, (*TWhereClause)(unsafe.Pointer(pWC)).Fa, pOld, uint32(48)*libc.Uint32FromInt32((*TWhereClause)(unsafe.Pointer(pWC)).FnTerm))
		(*TWhereClause)(unsafe.Pointer(pWC)).FnSlot = (*TWhereClause)(unsafe.Pointer(pWC)).FnSlot * int32(2)
	}
	v3 = pWC + 12
	v2 = *(*int32)(unsafe.Pointer(v3))
	*(*int32)(unsafe.Pointer(v3)) = *(*int32)(unsafe.Pointer(v3)) + 1
	v1 = v2
	idx = v1
	pTerm = (*TWhereClause)(unsafe.Pointer(pWC)).Fa + uintptr(v1)*48
	if libc.Int32FromUint16(wtFlags)&int32(TERM_VIRTUAL) == 0 {
		(*TWhereClause)(unsafe.Pointer(pWC)).FnBase = (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm
	}
	if p != 0 && (*TExpr)(unsafe.Pointer(p)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_Unlikely)) != uint32(0) {
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb = int16(int32(_sqlite3LogEst(tls, libc.Uint64FromInt32((*TExpr)(unsafe.Pointer(p)).FiTable))) - int32(270))
	} else {
		(*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb = int16(1)
	}
	(*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr = _sqlite3ExprSkipCollateAndLikely(tls, p)
	(*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags = wtFlags
	(*TWhereTerm)(unsafe.Pointer(pTerm)).FpWC = pWC
	(*TWhereTerm)(unsafe.Pointer(pTerm)).FiParent = -int32(1)
	libc.Xmemset(tls, pTerm+12, 0, libc.Uint32FromInt64(48)-uint32(libc.UintptrFromInt32(0)+12))
	return idx
}

// C documentation
//
//	/*
//	** Estimate the number of rows that will be returned based on
//	** an IN constraint where the right-hand side of the IN operator
//	** is a list of values.  Example:
//	**
//	**        WHERE x IN (1,2,3,4)
//	**
//	** Write the estimated row count into *pnRow and return SQLITE_OK.
//	** If unable to make an estimate, leave *pnRow unchanged and return
//	** non-zero.
//	**
//	** This routine can fail if it is unable to load a collating sequence
//	** required for string comparison, or if unable to allocate memory
//	** for a UTF conversion required for comparison.  The error is stored
//	** in the pParse structure.
//	*/
func _whereInScanEst(tls *libc.TLS, pParse uintptr, pBuilder uintptr, pList uintptr, pnRow uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, nRecValid, rc int32
	var nRow0 Ti64
	var nRowEst TtRowcnt
	var p uintptr
	var _ /* nEst at bp+0 */ TtRowcnt
	_, _, _, _, _, _ = i, nRecValid, nRow0, nRowEst, p, rc
	p = (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer((*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpNew + 24))).FpIndex
	nRow0 = libc.Int64FromUint64(_sqlite3LogEstToInt(tls, **(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(p)).FaiRowLogEst))))
	nRecValid = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FnRecValid
	rc = SQLITE_OK      /* Number of rows for a single term */
	nRowEst = uint64(0) /* Loop counter */
	i = 0
	for {
		if !(rc == SQLITE_OK && i < (*TExprList)(unsafe.Pointer(pList)).FnExpr) {
			break
		}
		**(**TtRowcnt)(__ccgo_up(bp)) = libc.Uint64FromInt64(nRow0)
		rc = _whereEqualScanEst(tls, pParse, pBuilder, (*(*TExprList_item)(unsafe.Pointer(pList + 8 + uintptr(i)*20))).FpExpr, bp)
		nRowEst = nRowEst + **(**TtRowcnt)(__ccgo_up(bp))
		(*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FnRecValid = nRecValid
		goto _1
	_1:
		;
		i = i + 1
	}
	if rc == SQLITE_OK {
		if nRowEst > libc.Uint64FromInt64(nRow0) {
			nRowEst = libc.Uint64FromInt64(nRow0)
		}
		**(**TtRowcnt)(__ccgo_up(pnRow)) = nRowEst
	}
	return rc
}

// C documentation
//
//	/*
//	** pIdx is an index that covers all of the low-number columns used by
//	** pWInfo->pSelect (columns from 0 through 62) or an index that has
//	** expressions terms.  Hence, we cannot determine whether or not it is
//	** a covering index by using the colUsed bitmasks.  We have to do a search
//	** to see if the index is covering.  This routine does that search.
//	**
//	** The return value is one of these:
//	**
//	**      0                The index is definitely not a covering index
//	**
//	**      WHERE_IDX_ONLY   The index is definitely a covering index
//	**
//	**      WHERE_EXPRIDX    The index is likely a covering index, but it is
//	**                       difficult to determine precisely because of the
//	**                       expressions that are indexed.  Score it as a
//	**                       covering index, but still keep the main table open
//	**                       just in case we need it.
//	**
//	** This routine is an optimization.  It is always safe to return zero.
//	** But returning one of the other two values when zero should have been
//	** returned can lead to incorrect bytecode and assertion faults.
//	*/
func _whereIsCoveringIndex(tls *libc.TLS, pWInfo uintptr, pIdx uintptr, iTabCur int32) (r Tu32) {
	bp := tls.Alloc(48)
	defer tls.Free(48)
	var i, rc int32
	var _ /* ck at bp+0 */ TCoveringIndexCheck
	var _ /* w at bp+12 */ TWalker
	_, _ = i, rc
	if (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpSelect == uintptr(0) {
		/* We don't have access to the full query, so we cannot check to see
		 ** if pIdx is covering.  Assume it is not. */
		return uint32(0)
	}
	if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x800>>11)) == 0 {
		i = 0
		for {
			if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)) {
				break
			}
			if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaiColumn + uintptr(i)*2))) >= libc.Int32FromUint32(libc.Uint32FromInt64(8)*libc.Uint32FromInt32(8))-libc.Int32FromInt32(1) {
				break
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		if i >= libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn) {
			/* pIdx does not index any columns greater than 62, but we know from
			 ** colMask that columns greater than 62 are used, so this is not a
			 ** covering index */
			return uint32(0)
		}
	}
	(**(**TCoveringIndexCheck)(__ccgo_up(bp))).FpIdx = pIdx
	(**(**TCoveringIndexCheck)(__ccgo_up(bp))).FiTabCur = iTabCur
	(**(**TCoveringIndexCheck)(__ccgo_up(bp))).FbExpr = uint8(0)
	(**(**TCoveringIndexCheck)(__ccgo_up(bp))).FbUnidx = uint8(0)
	libc.Xmemset(tls, bp+12, 0, uint32(28))
	(**(**TWalker)(__ccgo_up(bp + 12))).FxExprCallback = __ccgo_fp(_whereIsCoveringIndexWalkCallback)
	(**(**TWalker)(__ccgo_up(bp + 12))).FxSelectCallback = __ccgo_fp(_sqlite3SelectWalkNoop)
	*(*uintptr)(unsafe.Pointer(bp + 12 + 24)) = bp
	_sqlite3WalkSelect(tls, bp+12, (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpSelect)
	if (**(**TCoveringIndexCheck)(__ccgo_up(bp))).FbUnidx != 0 {
		rc = 0
	} else {
		if (**(**TCoveringIndexCheck)(__ccgo_up(bp))).FbExpr != 0 {
			rc = int32(WHERE_EXPRIDX)
		} else {
			rc = int32(WHERE_IDX_ONLY)
		}
	}
	return libc.Uint32FromInt32(rc)
}

// C documentation
//
//	/*
//	** Information passed in is pWalk->u.pCovIdxCk.  Call it pCk.
//	**
//	** If the Expr node references the table with cursor pCk->iTabCur, then
//	** make sure that column is covered by the index pCk->pIdx.  We know that
//	** all columns less than 63 (really BMS-1) are covered, so we don't need
//	** to check them.  But we do need to check any column at 63 or greater.
//	**
//	** If the index does not cover the column, then set pWalk->eCode to
//	** non-zero and return WRC_Abort to stop the search.
//	**
//	** If this node does not disprove that the index can be a covering index,
//	** then just return WRC_Continue, to continue the search.
//	**
//	** If pCk->pIdx contains indexed expressions and one of those expressions
//	** matches pExpr, then prune the search.
//	*/
func _whereIsCoveringIndexWalkCallback(tls *libc.TLS, pWalk uintptr, pExpr uintptr) (r int32) {
	var aiColumn, pCk, pIdx uintptr
	var i int32
	var nColumn Tu16
	_, _, _, _, _ = aiColumn, i, nColumn, pCk, pIdx /* Info about this search */
	pCk = *(*uintptr)(unsafe.Pointer(pWalk + 24))
	pIdx = (*TCoveringIndexCheck)(unsafe.Pointer(pCk)).FpIdx
	if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_COLUMN) || libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pExpr)).Fop) == int32(TK_AGG_COLUMN) {
		/* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
		if (*TExpr)(unsafe.Pointer(pExpr)).FiTable != (*TCoveringIndexCheck)(unsafe.Pointer(pCk)).FiTabCur {
			return WRC_Continue
		}
		pIdx = (*TCoveringIndexCheck)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pWalk + 24)))).FpIdx
		aiColumn = (*TIndex)(unsafe.Pointer(pIdx)).FaiColumn
		nColumn = (*TIndex)(unsafe.Pointer(pIdx)).FnColumn
		i = 0
		for {
			if !(i < libc.Int32FromUint16(nColumn)) {
				break
			}
			if int32(**(**Ti16)(__ccgo_up(aiColumn + uintptr(i)*2))) == int32((*TExpr)(unsafe.Pointer(pExpr)).FiColumn) {
				return WRC_Continue
			}
			goto _1
		_1:
			;
			i = i + 1
		}
		(*TCoveringIndexCheck)(unsafe.Pointer(pCk)).FbUnidx = uint8(1)
		return int32(WRC_Abort)
	} else {
		if int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x800>>11)) != 0 && _exprIsCoveredByIndex(tls, pExpr, pIdx, (*TCoveringIndexCheck)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pWalk + 24)))).FiTabCur) != 0 {
			(*TCoveringIndexCheck)(unsafe.Pointer(pCk)).FbExpr = uint8(1)
			return int32(WRC_Prune)
		}
	}
	return WRC_Continue
}

// C documentation
//
//	/*
//	** Estimate the location of a particular key among all keys in an
//	** index.  Store the results in aStat as follows:
//	**
//	**    aStat[0]      Est. number of rows less than pRec
//	**    aStat[1]      Est. number of rows equal to pRec
//	**
//	** Return the index of the sample that is the smallest sample that
//	** is greater than or equal to pRec. Note that this index is not an index
//	** into the aSample[] array - it is an index into a virtual set of samples
//	** based on the contents of aSample[] and the number of fields in record
//	** pRec.
//	*/
func _whereKeyStats(tls *libc.TLS, pParse uintptr, pIdx uintptr, pRec uintptr, roundUp int32, aStat uintptr) (r int32) {
	var aSample uintptr
	var i, iCol, iMin, iSamp, iSample, iTest, n, nField, res, v1 int32
	var iGap, iLower, iUpper TtRowcnt
	_, _, _, _, _, _, _, _, _, _, _, _, _, _ = aSample, i, iCol, iGap, iLower, iMin, iSamp, iSample, iTest, iUpper, n, nField, res, v1
	aSample = (*TIndex)(unsafe.Pointer(pIdx)).FaSample /* Smallest sample larger than or equal to pRec */
	iMin = 0                                           /* Number of fields in pRec */
	iLower = uint64(0)                                 /* anLt[] + anEq[] of largest sample pRec is > */
	_ = pParse
	/* Do a binary search to find the first sample greater than or equal
	 ** to pRec. If pRec contains a single field, the set of samples to search
	 ** is simply the aSample[] array. If the samples in aSample[] contain more
	 ** than one fields, all fields following the first are ignored.
	 **
	 ** If pRec contains N fields, where N is more than one, then as well as the
	 ** samples in aSample[] (truncated to N fields), the search also has to
	 ** consider prefixes of those samples. For example, if the set of samples
	 ** in aSample is:
	 **
	 **     aSample[0] = (a, 5)
	 **     aSample[1] = (a, 10)
	 **     aSample[2] = (b, 5)
	 **     aSample[3] = (c, 100)
	 **     aSample[4] = (c, 105)
	 **
	 ** Then the search space should ideally be the samples above and the
	 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
	 ** the code actually searches this set:
	 **
	 **     0: (a)
	 **     1: (a, 5)
	 **     2: (a, 10)
	 **     3: (a, 10)
	 **     4: (b)
	 **     5: (b, 5)
	 **     6: (c)
	 **     7: (c, 100)
	 **     8: (c, 105)
	 **     9: (c, 105)
	 **
	 ** For each sample in the aSample[] array, N samples are present in the
	 ** effective sample array. In the above, samples 0 and 1 are based on
	 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
	 **
	 ** Often, sample i of each block of N effective samples has (i+1) fields.
	 ** Except, each sample may be extended to ensure that it is greater than or
	 ** equal to the previous sample in the array. For example, in the above,
	 ** sample 2 is the first sample of a block of N samples, so at first it
	 ** appears that it should be 1 field in size. However, that would make it
	 ** smaller than sample 1, so the binary search would not work. As a result,
	 ** it is extended to two fields. The duplicates that this creates do not
	 ** cause any problems.
	 */
	if !((*TTable)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pIdx)).FpTable)).FtabFlags&libc.Uint32FromInt32(TF_WithoutRowid) == libc.Uint32FromInt32(0)) && int32(uint32(*(*uint16)(unsafe.Pointer(pIdx + 56))&0x3>>0)) == int32(SQLITE_IDXTYPE_PRIMARYKEY) {
		nField = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnKeyCol)
	} else {
		nField = libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pIdx)).FnColumn)
	}
	if libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(pRec)).FnField) < nField {
		v1 = libc.Int32FromUint16((*TUnpackedRecord)(unsafe.Pointer(pRec)).FnField)
	} else {
		v1 = nField
	}
	nField = v1
	iCol = 0
	iSample = (*TIndex)(unsafe.Pointer(pIdx)).FnSample * nField
	for cond := true; cond; cond = res != 0 && iMin < iSample { /* Number of fields in test sample */
		iTest = (iMin + iSample) / int32(2)
		iSamp = iTest / nField
		if iSamp > 0 {
			/* The proposed effective sample is a prefix of sample aSample[iSamp].
			 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
			 ** fields that is greater than the previous effective sample.  */
			n = iTest%nField + int32(1)
			for {
				if !(n < nField) {
					break
				}
				if **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp-int32(1))*20))).FanLt + uintptr(n-int32(1))*8)) != **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).FanLt + uintptr(n-int32(1))*8)) {
					break
				}
				goto _2
			_2:
				;
				n = n + 1
			}
		} else {
			n = iTest + int32(1)
		}
		(*TUnpackedRecord)(unsafe.Pointer(pRec)).FnField = libc.Uint16FromInt32(n)
		res = _sqlite3VdbeRecordCompare(tls, (**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).Fn, (**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).Fp, pRec)
		if res < 0 {
			iLower = **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).FanLt + uintptr(n-int32(1))*8)) + **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).FanEq + uintptr(n-int32(1))*8))
			iMin = iTest + int32(1)
		} else {
			if res == 0 && n < nField {
				iLower = **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(iSamp)*20))).FanLt + uintptr(n-int32(1))*8))
				iMin = iTest + int32(1)
				res = -int32(1)
			} else {
				iSample = iTest
				iCol = n - int32(1)
			}
		}
	}
	i = iSample / nField
	if res == 0 {
		/* Record pRec is equal to sample i */
		**(**TtRowcnt)(__ccgo_up(aStat)) = **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i)*20))).FanLt + uintptr(iCol)*8))
		**(**TtRowcnt)(__ccgo_up(aStat + 1*8)) = **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i)*20))).FanEq + uintptr(iCol)*8))
	} else {
		if i >= (*TIndex)(unsafe.Pointer(pIdx)).FnSample {
			iUpper = (*TIndex)(unsafe.Pointer(pIdx)).FnRowEst0
		} else {
			iUpper = **(**TtRowcnt)(__ccgo_up((**(**TIndexSample)(__ccgo_up(aSample + uintptr(i)*20))).FanLt + uintptr(iCol)*8))
		}
		if iLower >= iUpper {
			iGap = uint64(0)
		} else {
			iGap = iUpper - iLower
		}
		if roundUp != 0 {
			iGap = iGap * uint64(2) / uint64(3)
		} else {
			iGap = iGap / uint64(3)
		}
		**(**TtRowcnt)(__ccgo_up(aStat)) = iLower + iGap
		**(**TtRowcnt)(__ccgo_up(aStat + 1*8)) = **(**TtRowcnt)(__ccgo_up((*TIndex)(unsafe.Pointer(pIdx)).FaAvgEq + uintptr(nField-int32(1))*8))
	}
	/* Restore the pRec->nField value before returning.  */
	(*TUnpackedRecord)(unsafe.Pointer(pRec)).FnField = libc.Uint16FromInt32(nField)
	return i
}

// C documentation
//
//	/*
//	** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
//	** index pIndex. Try to match one more.
//	**
//	** When this function is called, pBuilder->pNew->nOut contains the
//	** number of rows expected to be visited by filtering using the nEq
//	** terms only. If it is modified, this value is restored before this
//	** function returns.
//	**
//	** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
//	** a fake index used for the INTEGER PRIMARY KEY.
//	*/
func _whereLoopAddBtreeIndex(tls *libc.TLS, pBuilder uintptr, pSrc uintptr, pProbe uintptr, nInMul TLogEst) (r int32) {
	bp := tls.Alloc(112)
	defer tls.Free(112)
	var M, logK, nIter, nOutUnadjusted, rCostIdx, rLogSize, rSize, saved_nOut, x TLogEst
	var bRedundant, i, iCol, nEq, nIn, nRecValid, nVecLen, opMask, rc, v21 int32
	var db, pBtm, pExpr, pExpr1, pNew, pParse, pTerm, pTop, pWInfo, v2 uintptr
	var eOp, saved_nBtm, saved_nEq, saved_nLTerm, saved_nSkip, saved_nTop, v4 Tu16
	var saved_prereq TBitmask
	var saved_wsFlags Tu32
	var v22 bool
	var _ /* nOut at bp+96 */ TtRowcnt
	var _ /* scan at bp+0 */ TWhereScan
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = M, bRedundant, db, eOp, i, iCol, logK, nEq, nIn, nIter, nOutUnadjusted, nRecValid, nVecLen, opMask, pBtm, pExpr, pExpr1, pNew, pParse, pTerm, pTop, pWInfo, rCostIdx, rLogSize, rSize, rc, saved_nBtm, saved_nEq, saved_nLTerm, saved_nOut, saved_nSkip, saved_nTop, saved_prereq, saved_wsFlags, x, v2, v21, v22, v4
	pWInfo = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWInfo /* WHERE analyze context */
	pParse = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpParse          /* Parsing context */
	db = (*TParse)(unsafe.Pointer(pParse)).Fdb                      /* Original value of pNew->nOut */
	rc = SQLITE_OK                                                  /* Logarithm of table size */
	pTop = uintptr(0)
	pBtm = uintptr(0) /* Top and bottom range constraints */
	pNew = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpNew
	if (*TParse)(unsafe.Pointer(pParse)).FnErr != 0 {
		return (*TParse)(unsafe.Pointer(pParse)).Frc
	}
	if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&uint32(WHERE_BTM_LIMIT) != 0 {
		opMask = libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LT)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LE)-libc.Int32FromInt32(TK_EQ))
	} else {
		opMask = libc.Int32FromInt32(WO_EQ) | libc.Int32FromInt32(WO_IN) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GT)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GE)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LT)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LE)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_ISNULL) | libc.Int32FromInt32(WO_IS)
	}
	if int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x4>>2)) != 0 {
		opMask = opMask & ^(libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GT)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GE)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LT)-libc.Int32FromInt32(TK_EQ)) | libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LE)-libc.Int32FromInt32(TK_EQ)))
	}
	saved_nEq = (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnEq
	saved_nBtm = (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnBtm
	saved_nTop = (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnTop
	saved_nSkip = (*TWhereLoop)(unsafe.Pointer(pNew)).FnSkip
	saved_nLTerm = (*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm
	saved_wsFlags = (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags
	saved_prereq = (*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq
	saved_nOut = (*TWhereLoop)(unsafe.Pointer(pNew)).FnOut
	pTerm = _whereScanInit(tls, bp, (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWC, (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor, libc.Int32FromUint16(saved_nEq), libc.Uint32FromInt32(opMask), pProbe)
	(*TWhereLoop)(unsafe.Pointer(pNew)).FrSetup = 0
	rSize = **(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst))
	rLogSize = _estLog(tls, rSize)
	for {
		if !(rc == SQLITE_OK && pTerm != uintptr(0)) {
			break
		}
		eOp = (*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator /* nOut before IN() and WHERE adjustments */
		nIn = 0
		nRecValid = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FnRecValid
		if (libc.Int32FromUint16(eOp) == int32(WO_ISNULL) || libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_VNULL) != 0) && _indexColumnNotNull(tls, pProbe, libc.Int32FromUint16(saved_nEq)) != 0 {
			goto _1 /* ignore IS [NOT] NULL constraints on NOT NULL columns */
		}
		if (*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqRight&(*TWhereLoop)(unsafe.Pointer(pNew)).FmaskSelf != 0 {
			goto _1
		}
		/* Do not allow the upper bound of a LIKE optimization range constraint
		 ** to mix with a lower range bound from some other source */
		if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_LIKEOPT) != 0 && libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator) == libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_LT)-libc.Int32FromInt32(TK_EQ)) {
			goto _1
		}
		if libc.Int32FromUint8((*TSrcItem)(unsafe.Pointer(pSrc)).Ffg.Fjointype)&(libc.Int32FromInt32(JT_LEFT)|libc.Int32FromInt32(JT_LTORJ)|libc.Int32FromInt32(JT_RIGHT)) != 0 && !(_constraintCompatibleWithOuterJoin(tls, pTerm, pSrc) != 0) {
			goto _1
		}
		if libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pProbe)).FonError) != OE_None && libc.Int32FromUint16(saved_nEq) == libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnKeyCol)-int32(1) {
			v2 = pBuilder + 24
			*(*uint8)(unsafe.Pointer(v2)) = uint8(int32(*(*uint8)(unsafe.Pointer(v2))) | libc.Int32FromInt32(SQLITE_BLDF1_UNIQUE))
		} else {
			v2 = pBuilder + 24
			*(*uint8)(unsafe.Pointer(v2)) = uint8(int32(*(*uint8)(unsafe.Pointer(v2))) | libc.Int32FromInt32(SQLITE_BLDF1_INDEXED))
		}
		(*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags = saved_wsFlags
		(*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq = saved_nEq
		(*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnBtm = saved_nBtm
		(*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnTop = saved_nTop
		(*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm = saved_nLTerm
		if libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm) >= libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLSlot) && _whereLoopResize(tls, db, pNew, libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm)+int32(1)) != 0 {
			break /* OOM while trying to enlarge the pNew->aLTerm array */
		}
		v2 = pNew + 44
		v4 = *(*Tu16)(unsafe.Pointer(v2))
		*(*Tu16)(unsafe.Pointer(v2)) = *(*Tu16)(unsafe.Pointer(v2)) + 1
		**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(v4)*4)) = pTerm
		(*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq = (saved_prereq | (*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqRight) & ^(*TWhereLoop)(unsafe.Pointer(pNew)).FmaskSelf
		if libc.Int32FromUint16(eOp)&int32(WO_IN) != 0 {
			pExpr = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
			if (*TExpr)(unsafe.Pointer(pExpr)).Fflags&uint32(EP_xIsSelect) != uint32(0) {
				bRedundant = 0
				nIn = int32(46)
				/* The expression may actually be of the form (x, y) IN (SELECT...).
				 ** In this case there is a separate term for each of (x) and (y).
				 ** However, the nIn multiplier should only be applied once, not once
				 ** for each such term. The following loop checks that pTerm is the
				 ** first such term in use, and sets nIn back to 0 if it is not. */
				i = 0
				for {
					if !(i < libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm)-int32(1)) {
						break
					}
					if **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(i)*4)) != 0 && (*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(i)*4)))).FpExpr == pExpr {
						nIn = 0
						if (*(*struct {
							FleftColumn int32
							FiField     int32
						})(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(i)*4)) + 24))).FiField == (*(*struct {
							FleftColumn int32
							FiField     int32
						})(unsafe.Pointer(pTerm + 24))).FiField {
							/* Detect when two or more columns of an index match the same
							 ** column of a vector IN operater, and avoid adding the column
							 ** to the WhereLoop more than once.  See tag-20250707-01
							 ** in test/rowvalue.test */
							bRedundant = int32(1)
						}
					}
					goto _6
				_6:
					;
					i = i + 1
				}
				if bRedundant != 0 {
					(*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm = (*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm - 1
					goto _1
				}
			} else {
				if *(*uintptr)(unsafe.Pointer(pExpr + 20)) != 0 && (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FnExpr != 0 {
					/* "x IN (value, value, ...)" */
					nIn = int32(_sqlite3LogEst(tls, libc.Uint64FromInt32((*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pExpr + 20)))).FnExpr)))
				}
			}
			if int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x80>>7)) != 0 && int32(rLogSize) >= int32(10) {
				/* Let:
				 **   N = the total number of rows in the table
				 **   K = the number of entries on the RHS of the IN operator
				 **   M = the number of rows in the table that match terms to the
				 **       to the left in the same index.  If the IN operator is on
				 **       the left-most index column, M==N.
				 **
				 ** Given the definitions above, it is better to omit the IN operator
				 ** from the index lookup and instead do a scan of the M elements,
				 ** testing each scanned row against the IN operator separately, if:
				 **
				 **        M*log(K) < K*log(N)
				 **
				 ** Our estimates for M, K, and N might be inaccurate, so we build in
				 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
				 ** with the index, as using an index has better worst-case behavior.
				 ** If we do not have real sqlite_stat1 data, always prefer to use
				 ** the index.  Do not bother with this optimization on very small
				 ** tables (less than 2 rows) as it is pointless in that case.
				 */
				M = **(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(saved_nEq)*2))
				logK = _estLog(tls, int16(nIn))
				/* TUNING      v-----  10 to bias toward indexed IN */
				x = int16(int32(M) + int32(logK) + int32(10) - (nIn + int32(rLogSize)))
				if int32(x) >= 0 {
				} else {
					if int32(nInMul) < int32(2) && (*Tsqlite3)(unsafe.Pointer(db)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_SeekScan)) == uint32(0) {
						**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_IN_SEEKSCAN)
					} else {
						goto _1
					}
				}
			}
			**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_COLUMN_IN)
		} else {
			if libc.Int32FromUint16(eOp)&(libc.Int32FromInt32(WO_EQ)|libc.Int32FromInt32(WO_IS)) != 0 {
				iCol = int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiColumn + uintptr(saved_nEq)*2)))
				**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_COLUMN_EQ)
				if iCol == -int32(1) || iCol >= 0 && int32(nInMul) == 0 && libc.Int32FromUint16(saved_nEq) == libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnKeyCol)-int32(1) {
					if iCol == -int32(1) || int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x8>>3)) != 0 || libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnKeyCol) == int32(1) && (*TIndex)(unsafe.Pointer(pProbe)).FonError != 0 && libc.Int32FromUint16(eOp)&int32(WO_EQ) != 0 {
						**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_ONEROW)
					} else {
						**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_UNQ_WANTED)
					}
				}
				if libc.Int32FromUint8((**(**TWhereScan)(__ccgo_up(bp))).FiEquiv) > int32(1) {
					**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_TRANSCONS)
				}
			} else {
				if libc.Int32FromUint16(eOp)&int32(WO_ISNULL) != 0 {
					**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_COLUMN_NULL)
				} else {
					nVecLen = _whereRangeVectorLen(tls, pParse, (*TSrcItem)(unsafe.Pointer(pSrc)).FiCursor, pProbe, libc.Int32FromUint16(saved_nEq), pTerm)
					if libc.Int32FromUint16(eOp)&(libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GT)-libc.Int32FromInt32(TK_EQ))|libc.Int32FromInt32(WO_EQ)<<(libc.Int32FromInt32(TK_GE)-libc.Int32FromInt32(TK_EQ))) != 0 {
						**(**Tu32)(__ccgo_up(pNew + 40)) |= libc.Uint32FromInt32(libc.Int32FromInt32(WHERE_COLUMN_RANGE) | libc.Int32FromInt32(WHERE_BTM_LIMIT))
						(*(*struct {
							FnEq          Tu16
							FnBtm         Tu16
							FnTop         Tu16
							FnDistinctCol Tu16
							FpIndex       uintptr
							FpOrderBy     uintptr
						})(unsafe.Pointer(pNew + 24))).FnBtm = libc.Uint16FromInt32(nVecLen)
						pBtm = pTerm
						pTop = uintptr(0)
						if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_LIKEOPT) != 0 {
							/* Range constraints that come from the LIKE optimization are
							 ** always used in pairs. */
							pTop = pTerm + 1*48
							if _whereLoopResize(tls, db, pNew, libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm)+int32(1)) != 0 {
								break
							} /* OOM */
							v2 = pNew + 44
							v4 = *(*Tu16)(unsafe.Pointer(v2))
							*(*Tu16)(unsafe.Pointer(v2)) = *(*Tu16)(unsafe.Pointer(v2)) + 1
							**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(v4)*4)) = pTop
							**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_TOP_LIMIT)
							(*(*struct {
								FnEq          Tu16
								FnBtm         Tu16
								FnTop         Tu16
								FnDistinctCol Tu16
								FpIndex       uintptr
								FpOrderBy     uintptr
							})(unsafe.Pointer(pNew + 24))).FnTop = uint16(1)
						}
					} else {
						**(**Tu32)(__ccgo_up(pNew + 40)) |= libc.Uint32FromInt32(libc.Int32FromInt32(WHERE_COLUMN_RANGE) | libc.Int32FromInt32(WHERE_TOP_LIMIT))
						(*(*struct {
							FnEq          Tu16
							FnBtm         Tu16
							FnTop         Tu16
							FnDistinctCol Tu16
							FpIndex       uintptr
							FpOrderBy     uintptr
						})(unsafe.Pointer(pNew + 24))).FnTop = libc.Uint16FromInt32(nVecLen)
						pTop = pTerm
						if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&uint32(WHERE_BTM_LIMIT) != uint32(0) {
							v2 = **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm)-int32(2))*4))
						} else {
							v2 = uintptr(0)
						}
						pBtm = v2
					}
				}
			}
		}
		/* At this point pNew->nOut is set to the number of rows expected to
		 ** be visited by the index scan before considering term pTerm, or the
		 ** values of nIn and nInMul. In other words, assuming that all
		 ** "x IN(...)" terms are replaced with "x = ?". This block updates
		 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
		if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&uint32(WHERE_COLUMN_RANGE) != 0 {
			/* Adjust nOut using stat4 data. Or, if there is no stat4
			 ** data, using some other estimate.  */
			_whereRangeScanEst(tls, pParse, pBuilder, pBtm, pTop, pNew)
		} else {
			v2 = pNew + 24
			*(*Tu16)(unsafe.Pointer(v2)) = *(*Tu16)(unsafe.Pointer(v2)) + 1
			v4 = *(*Tu16)(unsafe.Pointer(v2))
			nEq = libc.Int32FromUint16(v4)
			if int32((*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb) <= 0 && int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiColumn + uintptr(saved_nEq)*2))) >= 0 {
				v2 = pNew + 22
				*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) + int32((*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb))
				v2 = pNew + 22
				*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) - nIn)
			} else {
				**(**TtRowcnt)(__ccgo_up(bp + 96)) = uint64(0)
				if int32(nInMul) == 0 && (*TIndex)(unsafe.Pointer(pProbe)).FnSample != 0 && libc.Int32FromUint16((*(*struct {
					FnEq          Tu16
					FnBtm         Tu16
					FnTop         Tu16
					FnDistinctCol Tu16
					FpIndex       uintptr
					FpOrderBy     uintptr
				})(unsafe.Pointer(pNew + 24))).FnEq) <= (*TIndex)(unsafe.Pointer(pProbe)).FnSampleCol && (libc.Int32FromUint16(eOp)&int32(WO_IN) == 0 || (*TExpr)(unsafe.Pointer((*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr)).Fflags&uint32(EP_xIsSelect) == uint32(0)) && (*Tsqlite3)(unsafe.Pointer(db)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_Stat4)) == uint32(0) {
					pExpr1 = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
					if libc.Int32FromUint16(eOp)&(libc.Int32FromInt32(WO_EQ)|libc.Int32FromInt32(WO_ISNULL)|libc.Int32FromInt32(WO_IS)) != 0 {
						rc = _whereEqualScanEst(tls, pParse, pBuilder, (*TExpr)(unsafe.Pointer(pExpr1)).FpRight, bp+96)
					} else {
						rc = _whereInScanEst(tls, pParse, pBuilder, *(*uintptr)(unsafe.Pointer(pExpr1 + 20)), bp+96)
					}
					if rc == int32(SQLITE_NOTFOUND) {
						rc = SQLITE_OK
					}
					if rc != SQLITE_OK {
						break
					} /* Jump out of the pTerm loop */
					if **(**TtRowcnt)(__ccgo_up(bp + 96)) != 0 {
						(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = _sqlite3LogEst(tls, **(**TtRowcnt)(__ccgo_up(bp + 96)))
						if nEq == int32(1) && int32((*TWhereLoop)(unsafe.Pointer(pNew)).FnOut)+int32(10) > int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst))) {
							v2 = pTerm + 10
							*(*Tu16)(unsafe.Pointer(v2)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v2))) | libc.Int32FromInt32(TERM_HIGHTRUTH))
							if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_HEURTRUTH) != 0 {
								/* If the term has previously been used with an assumption of
								 ** higher selectivity, then set the flag to rerun the
								 ** loop computations. */
								v2 = pBuilder + 25
								*(*uint8)(unsafe.Pointer(v2)) = uint8(int32(*(*uint8)(unsafe.Pointer(v2))) | libc.Int32FromInt32(SQLITE_BLDF2_2NDPASS))
							}
						}
						if int32((*TWhereLoop)(unsafe.Pointer(pNew)).FnOut) > int32(saved_nOut) {
							(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = saved_nOut
						}
						v2 = pNew + 22
						*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) - nIn)
					}
				}
				if **(**TtRowcnt)(__ccgo_up(bp + 96)) == uint64(0) {
					v2 = pNew + 22
					*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) + (int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(nEq)*2))) - int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(nEq-int32(1))*2)))))
					if libc.Int32FromUint16(eOp)&int32(WO_ISNULL) != 0 {
						/* TUNING: If there is no likelihood() value, assume that a
						 ** "col IS NULL" expression matches twice as many rows
						 ** as (col=?). */
						v2 = pNew + 22
						*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) + libc.Int32FromInt32(10))
					}
				}
			}
		}
		/* Set rCostIdx to the estimated cost of visiting selected rows in the
		 ** index.  The estimate is the sum of two values:
		 **   1.  The cost of doing one search-by-key to find the first matching
		 **       entry
		 **   2.  Stepping forward in the index pNew->nOut times to find all
		 **       additional matching entries.
		 */
		if int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x3>>0)) == int32(SQLITE_IDXTYPE_IPK) {
			/* The pProbe->szIdxRow is low for an IPK table since the interior
			 ** pages are small.  Thus szIdxRow gives a good estimate of seek cost.
			 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
			 ** under-estimate the scanning cost. */
			rCostIdx = int16(int32((*TWhereLoop)(unsafe.Pointer(pNew)).FnOut) + int32(16))
		} else {
			rCostIdx = int16(int32((*TWhereLoop)(unsafe.Pointer(pNew)).FnOut) + int32(1) + int32(15)*int32((*TIndex)(unsafe.Pointer(pProbe)).FszIdxRow)/int32((*TTable)(unsafe.Pointer((*TSrcItem)(unsafe.Pointer(pSrc)).FpSTab)).FszTabRow))
		}
		rCostIdx = _sqlite3LogEstAdd(tls, rLogSize, rCostIdx)
		/* Estimate the cost of running the loop.  If all data is coming
		 ** from the index, then this is just the cost of doing the index
		 ** lookup and scan.  But if some data is coming out of the main table,
		 ** we also have to add in the cost of doing pNew->nOut searches to
		 ** locate the row in the main table that corresponds to the index entry.
		 */
		(*TWhereLoop)(unsafe.Pointer(pNew)).FrRun = rCostIdx
		if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&libc.Uint32FromInt32(libc.Int32FromInt32(WHERE_IDX_ONLY)|libc.Int32FromInt32(WHERE_IPK)|libc.Int32FromInt32(WHERE_EXPRIDX)) == uint32(0) {
			(*TWhereLoop)(unsafe.Pointer(pNew)).FrRun = _sqlite3LogEstAdd(tls, (*TWhereLoop)(unsafe.Pointer(pNew)).FrRun, int16(int32((*TWhereLoop)(unsafe.Pointer(pNew)).FnOut)+int32(16)))
		}
		nOutUnadjusted = (*TWhereLoop)(unsafe.Pointer(pNew)).FnOut
		v2 = pNew + 20
		*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) + (int32(nInMul) + nIn))
		v2 = pNew + 22
		*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) + (int32(nInMul) + nIn))
		_whereLoopOutputAdjust(tls, (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWC, pNew, rSize)
		if int32(*(*uint32)(unsafe.Pointer(pSrc + 12 + 4))&0x40000>>18) != 0 {
			(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = 0
		}
		rc = _whereLoopInsert(tls, pBuilder, pNew)
		if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&uint32(WHERE_COLUMN_RANGE) != 0 {
			(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = saved_nOut
		} else {
			(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = nOutUnadjusted
		}
		if (*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags&uint32(WHERE_TOP_LIMIT) == uint32(0) && libc.Int32FromUint16((*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq) < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnColumn) && (libc.Int32FromUint16((*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq) < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnKeyCol) || int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x3>>0)) != int32(SQLITE_IDXTYPE_PRIMARYKEY)) {
			if libc.Int32FromUint16((*(*struct {
				FnEq          Tu16
				FnBtm         Tu16
				FnTop         Tu16
				FnDistinctCol Tu16
				FpIndex       uintptr
				FpOrderBy     uintptr
			})(unsafe.Pointer(pNew + 24))).FnEq) > int32(3) {
				_sqlite3ProgressCheck(tls, pParse)
			}
			_whereLoopAddBtreeIndex(tls, pBuilder, pSrc, pProbe, int16(int32(nInMul)+nIn))
		}
		(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = saved_nOut
		(*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FnRecValid = nRecValid
		goto _1
	_1:
		;
		pTerm = _whereScanNext(tls, bp)
	}
	(*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq = saved_prereq
	(*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnEq = saved_nEq
	(*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnBtm = saved_nBtm
	(*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pNew + 24))).FnTop = saved_nTop
	(*TWhereLoop)(unsafe.Pointer(pNew)).FnSkip = saved_nSkip
	(*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags = saved_wsFlags
	(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = saved_nOut
	(*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm = saved_nLTerm
	/* Consider using a skip-scan if there are no WHERE clause constraints
	 ** available for the left-most terms of the index, and if the average
	 ** number of repeats in the left-most terms is at least 18.
	 **
	 ** The magic number 18 is selected on the basis that scanning 17 rows
	 ** is almost always quicker than an index seek (even though if the index
	 ** contains fewer than 2^17 rows we assume otherwise in other parts of
	 ** the code). And, even if it is not, it should not be too much slower.
	 ** On the other hand, the extra seeks could end up being significantly
	 ** more expensive.  */
	if v22 = libc.Int32FromUint16(saved_nEq) == libc.Int32FromUint16(saved_nSkip) && libc.Int32FromUint16(saved_nEq)+int32(1) < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pProbe)).FnKeyCol) && libc.Int32FromUint16(saved_nEq) == libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm) && int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x40>>6)) == 0 && int32(uint32(*(*uint16)(unsafe.Pointer(pProbe + 56))&0x80>>7)) != 0 && (*Tsqlite3)(unsafe.Pointer(db)).FdbOptFlags&libc.Uint32FromInt32(libc.Int32FromInt32(SQLITE_SkipScan)) == uint32(0) && int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(libc.Int32FromUint16(saved_nEq)+int32(1))*2))) >= int32(42) && int32(*(*uint32)(unsafe.Pointer(pSrc + 12 + 4))&0x40000>>18) == 0; v22 {
		v21 = _whereLoopResize(tls, db, pNew, libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm)+int32(1))
		rc = v21
	}
	if v22 && v21 == SQLITE_OK {
		(*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq = (*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq + 1
		(*TWhereLoop)(unsafe.Pointer(pNew)).FnSkip = (*TWhereLoop)(unsafe.Pointer(pNew)).FnSkip + 1
		v2 = pNew + 44
		v4 = *(*Tu16)(unsafe.Pointer(v2))
		*(*Tu16)(unsafe.Pointer(v2)) = *(*Tu16)(unsafe.Pointer(v2)) + 1
		**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pNew)).FaLTerm + uintptr(v4)*4)) = uintptr(0)
		**(**Tu32)(__ccgo_up(pNew + 40)) |= uint32(WHERE_SKIPSCAN)
		nIter = int16(int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(saved_nEq)*2))) - int32(**(**TLogEst)(__ccgo_up((*TIndex)(unsafe.Pointer(pProbe)).FaiRowLogEst + uintptr(libc.Int32FromUint16(saved_nEq)+int32(1))*2))))
		v2 = pNew + 22
		*(*TLogEst)(unsafe.Pointer(v2)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v2))) - int32(nIter))
		/* TUNING:  Because uncertainties in the estimates for skip-scan queries,
		 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
		nIter = int16(int32(nIter) + libc.Int32FromInt32(5))
		_whereLoopAddBtreeIndex(tls, pBuilder, pSrc, pProbe, int16(int32(nIter)+int32(nInMul)))
		(*TWhereLoop)(unsafe.Pointer(pNew)).FnOut = saved_nOut
		(*(*struct {
			FnEq          Tu16
			FnBtm         Tu16
			FnTop         Tu16
			FnDistinctCol Tu16
			FpIndex       uintptr
			FpOrderBy     uintptr
		})(unsafe.Pointer(pNew + 24))).FnEq = saved_nEq
		(*TWhereLoop)(unsafe.Pointer(pNew)).FnSkip = saved_nSkip
		(*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags = saved_wsFlags
	}
	return rc
}

// C documentation
//
//	/*
//	** Add all WhereLoop objects for a table of the join identified by
//	** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
//	**
//	** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
//	** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
//	** entries that occur before the virtual table in the FROM clause and are
//	** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
//	** mUnusable mask contains all FROM clause entries that occur after the
//	** virtual table and are separated from it by at least one LEFT or
//	** CROSS JOIN.
//	**
//	** For example, if the query were:
//	**
//	**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
//	**
//	** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
//	**
//	** All the tables in mPrereq must be scanned before the current virtual
//	** table. So any terms for which all prerequisites are satisfied by
//	** mPrereq may be specified as "usable" in all calls to xBestIndex.
//	** Conversely, all tables in mUnusable must be scanned after the current
//	** virtual table, so any terms for which the prerequisites overlap with
//	** mUnusable should always be configured as "not-usable" for xBestIndex.
//	*/
func _whereLoopAddVirtual(tls *libc.TLS, pBuilder uintptr, mPrereq TBitmask, mUnusable TBitmask) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var i, iTerm, nConstraint, rc, seenZero, seenZeroNoIN int32
	var mBest, mBestNoIn, mNext, mPrev, mThis, v1 TBitmask
	var p, pNew, pParse, pSrc, pWC, pWInfo uintptr
	var v2 bool
	var _ /* bIn at bp+0 */ int32
	var _ /* bRetry at bp+8 */ int32
	var _ /* mNoOmit at bp+4 */ Tu16
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = i, iTerm, mBest, mBestNoIn, mNext, mPrev, mThis, nConstraint, p, pNew, pParse, pSrc, pWC, pWInfo, rc, seenZero, seenZeroNoIN, v1, v2
	rc = SQLITE_OK
	**(**int32)(__ccgo_up(bp + 8)) = 0 /* True to retry with LIMIT/OFFSET disabled */
	pWInfo = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWInfo
	pParse = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpParse
	pWC = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpWC
	pNew = (*TWhereLoopBuilder)(unsafe.Pointer(pBuilder)).FpNew
	pSrc = (*TWhereInfo)(unsafe.Pointer(pWInfo)).FpTabList + 8 + uintptr((*TWhereLoop)(unsafe.Pointer(pNew)).FiTab)*48
	p = _allocateIndexInfo(tls, pWInfo, pWC, mUnusable, pSrc, bp+4)
	if p == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	(*TWhereLoop)(unsafe.Pointer(pNew)).FrSetup = 0
	(*TWhereLoop)(unsafe.Pointer(pNew)).FwsFlags = uint32(WHERE_VIRTUALTABLE)
	(*TWhereLoop)(unsafe.Pointer(pNew)).FnLTerm = uint16(0)
	libc.SetBitFieldPtr8Uint32(pNew+24+4, libc.Uint32FromInt32(0), 0, 0x1)
	nConstraint = (*Tsqlite3_index_info)(unsafe.Pointer(p)).FnConstraint
	if _whereLoopResize(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, pNew, nConstraint) != 0 {
		_freeIndexInfo(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, p)
		return int32(SQLITE_NOMEM)
	}
	/* First call xBestIndex() with all constraints usable. */
	rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, libc.Uint64FromInt32(-libc.Int32FromInt32(1)), uint16(0), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, bp+8)
	if **(**int32)(__ccgo_up(bp + 8)) != 0 {
		rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, libc.Uint64FromInt32(-libc.Int32FromInt32(1)), uint16(0), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, uintptr(0))
	}
	/* If the call to xBestIndex() with all terms enabled produced a plan
	 ** that does not require any source tables (IOW: a plan with mBest==0)
	 ** and does not use an IN(...) operator, then there is no point in making
	 ** any further calls to xBestIndex() since they will all return the same
	 ** result (if the xBestIndex() implementation is sane). */
	if v2 = rc == SQLITE_OK; v2 {
		v1 = (*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq & ^mPrereq
		mBest = v1
	}
	if v2 && (v1 != uint64(0) || **(**int32)(__ccgo_up(bp)) != 0) {
		seenZero = 0     /* True if a plan with no prereqs seen */
		seenZeroNoIN = 0 /* Plan with no prereqs and no IN(...) seen */
		mPrev = uint64(0)
		mBestNoIn = uint64(0)
		/* If the plan produced by the earlier call uses an IN(...) term, call
		 ** xBestIndex again, this time with IN(...) terms disabled. */
		if **(**int32)(__ccgo_up(bp)) != 0 {
			rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, libc.Uint64FromInt32(-libc.Int32FromInt32(1)), uint16(WO_IN), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, uintptr(0))
			mBestNoIn = (*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq & ^mPrereq
			if mBestNoIn == uint64(0) {
				seenZero = int32(1)
				seenZeroNoIN = int32(1)
			}
		}
		/* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
		 ** in the set of terms that apply to the current virtual table.  */
		for rc == SQLITE_OK {
			mNext = libc.Uint64FromInt32(-libc.Int32FromInt32(1))
			i = 0
			for {
				if !(i < nConstraint) {
					break
				}
				iTerm = (**(**Tsqlite3_index_constraint)(__ccgo_up((*Tsqlite3_index_info)(unsafe.Pointer(p)).FaConstraint + uintptr(i)*12))).FiTermOffset
				mThis = (*TWhereTerm)(unsafe.Pointer(_termFromWhereClause(tls, pWC, iTerm))).FprereqRight & ^mPrereq
				if mThis > mPrev && mThis < mNext {
					mNext = mThis
				}
				goto _3
			_3:
				;
				i = i + 1
			}
			mPrev = mNext
			if mNext == libc.Uint64FromInt32(-libc.Int32FromInt32(1)) {
				break
			}
			if mNext == mBest || mNext == mBestNoIn {
				continue
			}
			rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, mNext|mPrereq, uint16(0), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, uintptr(0))
			if (*TWhereLoop)(unsafe.Pointer(pNew)).Fprereq == mPrereq {
				seenZero = int32(1)
				if **(**int32)(__ccgo_up(bp)) == 0 {
					seenZeroNoIN = int32(1)
				}
			}
		}
		/* If the calls to xBestIndex() in the above loop did not find a plan
		 ** that requires no source tables at all (i.e. one guaranteed to be
		 ** usable), make a call here with all source tables disabled */
		if rc == SQLITE_OK && seenZero == 0 {
			rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, mPrereq, uint16(0), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, uintptr(0))
			if **(**int32)(__ccgo_up(bp)) == 0 {
				seenZeroNoIN = int32(1)
			}
		}
		/* If the calls to xBestIndex() have so far failed to find a plan
		 ** that requires no source tables at all and does not use an IN(...)
		 ** operator, make a final call to obtain one here.  */
		if rc == SQLITE_OK && seenZeroNoIN == 0 {
			rc = _whereLoopAddVirtualOne(tls, pBuilder, mPrereq, mPrereq, uint16(WO_IN), p, **(**Tu16)(__ccgo_up(bp + 4)), bp, uintptr(0))
		}
	}
	_freeIndexInfo(tls, (*TParse)(unsafe.Pointer(pParse)).Fdb, p)
	return rc
}

// C documentation
//
//	/*
//	** Return TRUE if X is a proper subset of Y but is of equal or less cost.
//	** In other words, return true if all constraints of X are also part of Y
//	** and Y has additional constraints that might speed the search that X lacks
//	** but the cost of running X is not more than the cost of running Y.
//	**
//	** In other words, return true if the cost relationship between X and Y
//	** is inverted and needs to be adjusted.
//	**
//	** Case 1:
//	**
//	**   (1a)  X and Y use the same index.
//	**   (1b)  X has fewer == terms than Y
//	**   (1c)  Neither X nor Y use skip-scan
//	**   (1d)  X does not have a a greater cost than Y
//	**
//	** Case 2:
//	**
//	**   (2a)  X has the same or lower cost, or returns the same or fewer rows,
//	**         than Y.
//	**   (2b)  X uses fewer WHERE clause terms than Y
//	**   (2c)  Every WHERE clause term used by X is also used by Y
//	**   (2d)  X skips at least as many columns as Y
//	**   (2e)  If X is a covering index, than Y is too
//	*/
func _whereLoopCheaperProperSubset(tls *libc.TLS, pX uintptr, pY uintptr) (r int32) {
	var i, j int32
	_, _ = i, j
	if int32((*TWhereLoop)(unsafe.Pointer(pX)).FrRun) > int32((*TWhereLoop)(unsafe.Pointer(pY)).FrRun) && int32((*TWhereLoop)(unsafe.Pointer(pX)).FnOut) > int32((*TWhereLoop)(unsafe.Pointer(pY)).FnOut) {
		return 0
	} /* (1d) and (2a) */
	if libc.Int32FromUint16((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pX + 24))).FnEq) < libc.Int32FromUint16((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pY + 24))).FnEq) && (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pX + 24))).FpIndex == (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pY + 24))).FpIndex && libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pX)).FnSkip) == 0 && libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pY)).FnSkip) == 0 {
		return int32(1) /* Case 1 is true */
	}
	if libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pX)).FnLTerm)-libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pX)).FnSkip) >= libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pY)).FnLTerm)-libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pY)).FnSkip) {
		return 0 /* (2b) */
	}
	if libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pY)).FnSkip) > libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pX)).FnSkip) {
		return 0
	} /* (2d) */
	i = libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pX)).FnLTerm) - int32(1)
	for {
		if !(i >= 0) {
			break
		}
		if **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pX)).FaLTerm + uintptr(i)*4)) == uintptr(0) {
			goto _1
		}
		j = libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pY)).FnLTerm) - int32(1)
		for {
			if !(j >= 0) {
				break
			}
			if **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pY)).FaLTerm + uintptr(j)*4)) == **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pX)).FaLTerm + uintptr(i)*4)) {
				break
			}
			goto _2
		_2:
			;
			j = j - 1
		}
		if j < 0 {
			return 0
		} /* (2c) */
		goto _1
	_1:
		;
		i = i - 1
	}
	if (*TWhereLoop)(unsafe.Pointer(pX)).FwsFlags&uint32(WHERE_IDX_ONLY) != uint32(0) && (*TWhereLoop)(unsafe.Pointer(pY)).FwsFlags&uint32(WHERE_IDX_ONLY) == uint32(0) {
		return 0 /* (2e) */
	}
	return int32(1) /* Case 2 is true */
}

// C documentation
//
//	/*
//	** Deallocate internal memory used by a WhereLoop object.  Leave the
//	** object in an initialized state, as if it had been newly allocated.
//	*/
func _whereLoopClear(tls *libc.TLS, db uintptr, p uintptr) {
	if (*TWhereLoop)(unsafe.Pointer(p)).FaLTerm != p+60 {
		_sqlite3DbFreeNN(tls, db, (*TWhereLoop)(unsafe.Pointer(p)).FaLTerm)
		(*TWhereLoop)(unsafe.Pointer(p)).FaLTerm = p + 60
		(*TWhereLoop)(unsafe.Pointer(p)).FnLSlot = libc.Uint16FromInt32(libc.Int32FromUint32(libc.Uint32FromInt64(12) / libc.Uint32FromInt64(4)))
	}
	_whereLoopClearUnion(tls, db, p)
	(*TWhereLoop)(unsafe.Pointer(p)).FnLTerm = uint16(0)
	(*TWhereLoop)(unsafe.Pointer(p)).FwsFlags = uint32(0)
}

// C documentation
//
//	/*
//	** Search the list of WhereLoops in *ppPrev looking for one that can be
//	** replaced by pTemplate.
//	**
//	** Return NULL if pTemplate does not belong on the WhereLoop list.
//	** In other words if pTemplate ought to be dropped from further consideration.
//	**
//	** If pX is a WhereLoop that pTemplate can replace, then return the
//	** link that points to pX.
//	**
//	** If pTemplate cannot replace any existing element of the list but needs
//	** to be added to the list as a new entry, then return a pointer to the
//	** tail of the list.
//	*/
func _whereLoopFindLesser(tls *libc.TLS, ppPrev uintptr, pTemplate uintptr) (r uintptr) {
	var p uintptr
	_ = p
	p = **(**uintptr)(__ccgo_up(ppPrev))
	for {
		if !(p != 0) {
			break
		}
		if libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(p)).FiTab) != libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(pTemplate)).FiTab) || libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(p)).FiSortIdx) != libc.Int32FromUint8((*TWhereLoop)(unsafe.Pointer(pTemplate)).FiSortIdx) {
			/* If either the iTab or iSortIdx values for two WhereLoop are different
			 ** then those WhereLoops need to be considered separately.  Neither is
			 ** a candidate to replace the other. */
			goto _1
		}
		/* In the current implementation, the rSetup value is either zero
		 ** or the cost of building an automatic index (NlogN) and the NlogN
		 ** is the same for compatible WhereLoops. */
		/* whereLoopAddBtree() always generates and inserts the automatic index
		 ** case first.  Hence compatible candidate WhereLoops never have a larger
		 ** rSetup. Call this SETUP-INVARIANT */
		/* Any loop using an application-defined index (or PRIMARY KEY or
		 ** UNIQUE constraint) with one or more == constraints is better
		 ** than an automatic index. Unless it is a skip-scan. */
		if (*TWhereLoop)(unsafe.Pointer(p)).FwsFlags&uint32(WHERE_AUTO_INDEX) != uint32(0) && libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pTemplate)).FnSkip) == 0 && (*TWhereLoop)(unsafe.Pointer(pTemplate)).FwsFlags&uint32(WHERE_INDEXED) != uint32(0) && (*TWhereLoop)(unsafe.Pointer(pTemplate)).FwsFlags&uint32(WHERE_COLUMN_EQ) != uint32(0) && (*TWhereLoop)(unsafe.Pointer(p)).Fprereq&(*TWhereLoop)(unsafe.Pointer(pTemplate)).Fprereq == (*TWhereLoop)(unsafe.Pointer(pTemplate)).Fprereq {
			break
		}
		/* If existing WhereLoop p is better than pTemplate, pTemplate can be
		 ** discarded.  WhereLoop p is better if:
		 **   (1)  p has no more dependencies than pTemplate, and
		 **   (2)  p has an equal or lower cost than pTemplate
		 */
		if (*TWhereLoop)(unsafe.Pointer(p)).Fprereq&(*TWhereLoop)(unsafe.Pointer(pTemplate)).Fprereq == (*TWhereLoop)(unsafe.Pointer(p)).Fprereq && int32((*TWhereLoop)(unsafe.Pointer(p)).FrSetup) <= int32((*TWhereLoop)(unsafe.Pointer(pTemplate)).FrSetup) && int32((*TWhereLoop)(unsafe.Pointer(p)).FrRun) <= int32((*TWhereLoop)(unsafe.Pointer(pTemplate)).FrRun) && int32((*TWhereLoop)(unsafe.Pointer(p)).FnOut) <= int32((*TWhereLoop)(unsafe.Pointer(pTemplate)).FnOut) {
			return uintptr(0) /* Discard pTemplate */
		}
		/* If pTemplate is always better than p, then cause p to be overwritten
		 ** with pTemplate.  pTemplate is better than p if:
		 **   (1)  pTemplate has no more dependencies than p, and
		 **   (2)  pTemplate has an equal or lower cost than p.
		 */
		if (*TWhereLoop)(unsafe.Pointer(p)).Fprereq&(*TWhereLoop)(unsafe.Pointer(pTemplate)).Fprereq == (*TWhereLoop)(unsafe.Pointer(pTemplate)).Fprereq && int32((*TWhereLoop)(unsafe.Pointer(p)).FrRun) >= int32((*TWhereLoop)(unsafe.Pointer(pTemplate)).FrRun) && int32((*TWhereLoop)(unsafe.Pointer(p)).FnOut) >= int32((*TWhereLoop)(unsafe.Pointer(pTemplate)).FnOut) {
			/* SETUP-INVARIANT above */
			break /* Cause p to be overwritten by pTemplate */
		}
		goto _1
	_1:
		;
		ppPrev = p + 56
		p = **(**uintptr)(__ccgo_up(ppPrev))
	}
	return ppPrev
}

// C documentation
//
//	/*
//	** Convert bulk memory into a valid WhereLoop that can be passed
//	** to whereLoopClear harmlessly.
//	*/
func _whereLoopInit(tls *libc.TLS, p uintptr) {
	(*TWhereLoop)(unsafe.Pointer(p)).FaLTerm = p + 60
	(*TWhereLoop)(unsafe.Pointer(p)).FnLTerm = uint16(0)
	(*TWhereLoop)(unsafe.Pointer(p)).FnLSlot = libc.Uint16FromInt32(libc.Int32FromUint32(libc.Uint32FromInt64(12) / libc.Uint32FromInt64(4)))
	(*TWhereLoop)(unsafe.Pointer(p)).FwsFlags = uint32(0)
}

// C documentation
//
//	/*
//	** Loop pLoop is a WHERE_INDEXED level that uses at least one IN(...)
//	** operator. Return true if level pLoop is guaranteed to visit only one
//	** row for each key generated for the index.
//	*/
func _whereLoopIsOneRow(tls *libc.TLS, pLoop uintptr) (r int32) {
	var ii int32
	_ = ii
	if (*TIndex)(unsafe.Pointer((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FpIndex)).FonError != 0 && libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pLoop)).FnSkip) == 0 && libc.Int32FromUint16((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FnEq) == libc.Int32FromUint16((*TIndex)(unsafe.Pointer((*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FpIndex)).FnKeyCol) {
		ii = 0
		for {
			if !(ii < libc.Int32FromUint16((*(*struct {
				FnEq          Tu16
				FnBtm         Tu16
				FnTop         Tu16
				FnDistinctCol Tu16
				FpIndex       uintptr
				FpOrderBy     uintptr
			})(unsafe.Pointer(pLoop + 24))).FnEq)) {
				break
			}
			if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(**(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(ii)*4)))).FeOperator)&(libc.Int32FromInt32(WO_IS)|libc.Int32FromInt32(WO_ISNULL)) != 0 {
				return 0
			}
			goto _1
		_1:
			;
			ii = ii + 1
		}
		return int32(1)
	}
	return 0
}

// C documentation
//
//	/*
//	** Adjust the WhereLoop.nOut value downward to account for terms of the
//	** WHERE clause that reference the loop but which are not used by an
//	** index.
//	*
//	** For every WHERE clause term that is not used by the index
//	** and which has a truth probability assigned by one of the likelihood(),
//	** likely(), or unlikely() SQL functions, reduce the estimated number
//	** of output rows by the probability specified.
//	**
//	** TUNING:  For every WHERE clause term that is not used by the index
//	** and which does not have an assigned truth probability, heuristics
//	** described below are used to try to estimate the truth probability.
//	** TODO --> Perhaps this is something that could be improved by better
//	** table statistics.
//	**
//	** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
//	** value corresponds to -1 in LogEst notation, so this means decrement
//	** the WhereLoop.nOut field for every such WHERE clause term.
//	**
//	** Heuristic 2:  If there exists one or more WHERE clause terms of the
//	** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
//	** final output row estimate is no greater than 1/4 of the total number
//	** of rows in the table.  In other words, assume that x==EXPR will filter
//	** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
//	** "x" column is boolean or else -1 or 0 or 1 is a common default value
//	** on the "x" column and so in that case only cap the output row estimate
//	** at 1/2 instead of 1/4.
//	**
//	** Heuristic 3:  If there is a LIKE or GLOB (or REGEXP or MATCH) operator
//	** with a large constant pattern, then reduce the size of the search
//	** space according to the length of the pattern, under the theory that
//	** longer patterns are less likely to match.  This heuristic was added
//	** to give better output-row count estimates when preparing queries for
//	** the Join-Order Benchmarks.  See forum thread 2026-01-30T09:57:54z
//	*/
func _whereLoopOutputAdjust(tls *libc.TLS, pWC uintptr, pLoop uintptr, nRow TLogEst) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var eOp, i, j, szPattern int32
	var iReduce TLogEst
	var notAllowed TBitmask
	var pOpExpr, pRHS, pRight, pTerm, pX, v3 uintptr
	var _ /* k at bp+0 */ int32
	_, _, _, _, _, _, _, _, _, _, _, _ = eOp, i, iReduce, j, notAllowed, pOpExpr, pRHS, pRight, pTerm, pX, szPattern, v3
	notAllowed = ^((*TWhereLoop)(unsafe.Pointer(pLoop)).Fprereq | (*TWhereLoop)(unsafe.Pointer(pLoop)).FmaskSelf)
	iReduce = 0 /* pLoop->nOut should not exceed nRow-iReduce */
	i = (*TWhereClause)(unsafe.Pointer(pWC)).FnBase
	pTerm = (*TWhereClause)(unsafe.Pointer(pWC)).Fa
	for {
		if !(i > 0) {
			break
		}
		if (*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqAll&notAllowed != uint64(0) {
			goto _1
		}
		if (*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqAll&(*TWhereLoop)(unsafe.Pointer(pLoop)).FmaskSelf == uint64(0) {
			goto _1
		}
		if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_VIRTUAL) != 0 {
			goto _1
		}
		j = libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pLoop)).FnLTerm) - int32(1)
		for {
			if !(j >= 0) {
				break
			}
			pX = **(**uintptr)(__ccgo_up((*TWhereLoop)(unsafe.Pointer(pLoop)).FaLTerm + uintptr(j)*4))
			if pX == uintptr(0) {
				goto _2
			}
			if pX == pTerm {
				break
			}
			if (*TWhereTerm)(unsafe.Pointer(pX)).FiParent >= 0 && (*TWhereClause)(unsafe.Pointer(pWC)).Fa+uintptr((*TWhereTerm)(unsafe.Pointer(pX)).FiParent)*48 == pTerm {
				break
			}
			goto _2
		_2:
			;
			j = j - 1
		}
		if j < 0 {
			_sqlite3ProgressCheck(tls, (*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpParse)
			if (*TWhereLoop)(unsafe.Pointer(pLoop)).FmaskSelf == (*TWhereTerm)(unsafe.Pointer(pTerm)).FprereqAll {
				/* If there are extra terms in the WHERE clause not used by an index
				 ** that depend only on the table being scanned, and that will tend to
				 ** cause many rows to be omitted, then mark that table as
				 ** "self-culling".
				 **
				 ** 2022-03-24:  Self-culling only applies if either the extra terms
				 ** are straight comparison operators that are non-true with NULL
				 ** operand, or if the loop is not an OUTER JOIN.
				 */
				if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator)&int32(0x3f) != 0 || libc.Int32FromUint8((*(*TSrcItem)(unsafe.Pointer((*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpTabList + 8 + uintptr((*TWhereLoop)(unsafe.Pointer(pLoop)).FiTab)*48))).Ffg.Fjointype)&(libc.Int32FromInt32(JT_LEFT)|libc.Int32FromInt32(JT_LTORJ)) == 0 {
					**(**Tu32)(__ccgo_up(pLoop + 40)) |= uint32(WHERE_SELFCULL)
				}
			}
			if int32((*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb) <= 0 {
				/* If a truth probability is specified using the likelihood() hints,
				 ** then use the probability provided by the application. */
				v3 = pLoop + 22
				*(*TLogEst)(unsafe.Pointer(v3)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v3))) + int32((*TWhereTerm)(unsafe.Pointer(pTerm)).FtruthProb))
			} else {
				/* In the absence of explicit truth probabilities, use heuristics to
				 ** guess a reasonable truth probability. */
				pOpExpr = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
				(*TWhereLoop)(unsafe.Pointer(pLoop)).FnOut = (*TWhereLoop)(unsafe.Pointer(pLoop)).FnOut - 1
				if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator)&(libc.Int32FromInt32(WO_EQ)|libc.Int32FromInt32(WO_IS)) != 0 && libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_HIGHTRUTH) == 0 {
					pRight = (*TExpr)(unsafe.Pointer(pOpExpr)).FpRight
					**(**int32)(__ccgo_up(bp)) = 0
					if _sqlite3ExprIsInteger(tls, pRight, bp, uintptr(0)) != 0 && **(**int32)(__ccgo_up(bp)) >= -int32(1) && **(**int32)(__ccgo_up(bp)) <= int32(1) {
						**(**int32)(__ccgo_up(bp)) = int32(10)
					} else {
						**(**int32)(__ccgo_up(bp)) = int32(20)
					}
					if int32(iReduce) < **(**int32)(__ccgo_up(bp)) {
						v3 = pTerm + 10
						*(*Tu16)(unsafe.Pointer(v3)) = Tu16(int32(*(*Tu16)(unsafe.Pointer(v3))) | libc.Int32FromInt32(TERM_HEURTRUTH))
						iReduce = int16(**(**int32)(__ccgo_up(bp)))
					}
				} else {
					if (*TExpr)(unsafe.Pointer(pOpExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_InfixFunc)) != uint32(0) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pOpExpr)).Fop) == int32(TK_FUNCTION) {
						eOp = _sqlite3ExprIsLikeOperator(tls, pOpExpr)
						if eOp > 0 {
							pRHS = (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(pOpExpr + 20)) + 8))).FpExpr
							eOp = libc.BoolInt32(eOp == int32(SQLITE_INDEX_CONSTRAINT_LIKE))
							szPattern = _estLikePatternLength(tls, pRHS, libc.Uint16FromInt32(eOp))
							if szPattern > 0 {
								v3 = pLoop + 22
								*(*TLogEst)(unsafe.Pointer(v3)) = TLogEst(int32(*(*TLogEst)(unsafe.Pointer(v3))) - szPattern*libc.Int32FromInt32(2))
							}
						}
					}
				}
			}
		}
		goto _1
	_1:
		;
		i = i - 1
		pTerm += 48
	}
	if int32((*TWhereLoop)(unsafe.Pointer(pLoop)).FnOut) > int32(nRow)-int32(iReduce) {
		(*TWhereLoop)(unsafe.Pointer(pLoop)).FnOut = int16(int32(nRow) - int32(iReduce))
	}
}

// C documentation
//
//	/*
//	** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
//	*/
func _whereLoopResize(tls *libc.TLS, db uintptr, p uintptr, n int32) (r int32) {
	var paNew uintptr
	_ = paNew
	if libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(p)).FnLSlot) >= n {
		return SQLITE_OK
	}
	n = (n + int32(7)) & ^libc.Int32FromInt32(7)
	paNew = _sqlite3DbMallocRawNN(tls, db, uint64(uint32(4)*libc.Uint32FromInt32(n)))
	if paNew == uintptr(0) {
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemcpy(tls, paNew, (*TWhereLoop)(unsafe.Pointer(p)).FaLTerm, uint32(4)*uint32((*TWhereLoop)(unsafe.Pointer(p)).FnLSlot))
	if (*TWhereLoop)(unsafe.Pointer(p)).FaLTerm != p+60 {
		_sqlite3DbFreeNN(tls, db, (*TWhereLoop)(unsafe.Pointer(p)).FaLTerm)
	}
	(*TWhereLoop)(unsafe.Pointer(p)).FaLTerm = paNew
	(*TWhereLoop)(unsafe.Pointer(p)).FnLSlot = libc.Uint16FromInt32(n)
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Transfer content from the second pLoop into the first.
//	*/
func _whereLoopXfer(tls *libc.TLS, db uintptr, pTo uintptr, pFrom uintptr) (r int32) {
	_whereLoopClearUnion(tls, db, pTo)
	if libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pFrom)).FnLTerm) > libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pTo)).FnLSlot) && _whereLoopResize(tls, db, pTo, libc.Int32FromUint16((*TWhereLoop)(unsafe.Pointer(pFrom)).FnLTerm)) != 0 {
		libc.Xmemset(tls, pTo, 0, uint32(libc.UintptrFromInt32(0)+48))
		return int32(SQLITE_NOMEM)
	}
	libc.Xmemcpy(tls, pTo, pFrom, uint32(libc.UintptrFromInt32(0)+48))
	libc.Xmemcpy(tls, (*TWhereLoop)(unsafe.Pointer(pTo)).FaLTerm, (*TWhereLoop)(unsafe.Pointer(pFrom)).FaLTerm, uint32((*TWhereLoop)(unsafe.Pointer(pTo)).FnLTerm)*uint32(4))
	if (*TWhereLoop)(unsafe.Pointer(pFrom)).FwsFlags&uint32(WHERE_VIRTUALTABLE) != 0 {
		libc.SetBitFieldPtr8Uint32(pFrom+24+4, libc.Uint32FromInt32(0), 0, 0x1)
	} else {
		if (*TWhereLoop)(unsafe.Pointer(pFrom)).FwsFlags&uint32(WHERE_AUTO_INDEX) != uint32(0) {
			(*(*struct {
				FnEq          Tu16
				FnBtm         Tu16
				FnTop         Tu16
				FnDistinctCol Tu16
				FpIndex       uintptr
				FpOrderBy     uintptr
			})(unsafe.Pointer(pFrom + 24))).FpIndex = uintptr(0)
		}
	}
	return SQLITE_OK
}

// C documentation
//
//	/*
//	** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
//	** a conjunction, then return just pTerm when N==0.  If N is exceeds
//	** the number of available subterms, return NULL.
//	*/
func _whereNthSubterm(tls *libc.TLS, pTerm uintptr, N int32) (r uintptr) {
	var v1 uintptr
	_ = v1
	if libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FeOperator) != int32(WO_AND) {
		if N == 0 {
			v1 = pTerm
		} else {
			v1 = uintptr(0)
		}
		return v1
	}
	if N < (*TWhereAndInfo)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TWhereTerm)(unsafe.Pointer(pTerm)).Fu)))).Fwc.FnTerm {
		return (*TWhereAndInfo)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&(*TWhereTerm)(unsafe.Pointer(pTerm)).Fu)))).Fwc.Fa + uintptr(N)*48
	}
	return uintptr(0)
}

// C documentation
//
//	/* Implementation of the order-by-subquery optimization:
//	**
//	** WhereLoop pLoop, which the iLoop-th term of the nested loop, is really
//	** a subquery or CTE that has an ORDER BY clause.  See if any of the terms
//	** in the subquery ORDER BY clause will satisfy pOrderBy from the outer
//	** query.  Mark off all satisfied terms (by setting bits in *pOBSat) and
//	** return TRUE if they do.  If not, return false.
//	**
//	** Example:
//	**
//	**    CREATE TABLE t1(a,b,c, PRIMARY KEY(a,b));
//	**    CREATE TABLE t2(x,y);
//	**    WITH t3(p,q) AS MATERIALIZED (SELECT x+y, x-y FROM t2 ORDER BY x+y)
//	**       SELECT * FROM t3 JOIN t1 ON a=q ORDER BY p, b;
//	**
//	** The CTE named "t3" comes out in the natural order of "p", so the first
//	** first them of "ORDER BY p,b" is satisfied by a sequential scan of "t3"
//	** and sorting only needs to occur on the second term "b".
//	**
//	** Limitations:
//	**
//	** (1)  The optimization is not applied if the outer ORDER BY contains
//	**      a COLLATE clause.  The optimization might be applied if the
//	**      outer ORDER BY uses NULLS FIRST, NULLS LAST, ASC, and/or DESC as
//	**      long as the subquery ORDER BY does the same.  But if the
//	**      outer ORDER BY uses COLLATE, even a redundant COLLATE, the
//	**      optimization is bypassed.
//	**
//	** (2)  The subquery ORDER BY terms must exactly match subquery result
//	**      columns, including any COLLATE annotations.  This routine relies
//	**      on iOrderByCol to do matching between order by terms and result
//	**      columns, and iOrderByCol will not be set if the result column
//	**      and ORDER BY collations differ.
//	**
//	** (3)  The subquery and outer ORDER BY can be in opposite directions as
//	**      long as  the subquery is materialized.  If the subquery is
//	**      implemented as a co-routine, the sort orders must be in the same
//	**      direction because there is no way to run a co-routine backwards.
//	*/
func _wherePathMatchSubqueryOB(tls *libc.TLS, pWInfo uintptr, pLoop uintptr, iLoop int32, iCur int32, pOrderBy uintptr, pRevMask uintptr, pOBSat uintptr) (r int32) {
	var iOB, jSub int32
	var pOBExpr, pSubOB uintptr
	var rev, revIdx, sfOB, sfSub Tu8
	_, _, _, _, _, _, _, _ = iOB, jSub, pOBExpr, pSubOB, rev, revIdx, sfOB, sfSub /* Index into pSubOB->a[] */
	rev = uint8(0)                                                                /* True if iOB and jSub sort in opposite directions */
	revIdx = uint8(0)                                                             /* Complete ORDER BY on the subquery */
	pSubOB = (*(*struct {
		FnEq          Tu16
		FnBtm         Tu16
		FnTop         Tu16
		FnDistinctCol Tu16
		FpIndex       uintptr
		FpOrderBy     uintptr
	})(unsafe.Pointer(pLoop + 24))).FpOrderBy
	iOB = 0
	for {
		if !(libc.Uint64FromInt32(1)<<iOB&**(**TBitmask)(__ccgo_up(pOBSat)) != uint64(0)) {
			break
		}
		goto _1
	_1:
		;
		iOB = iOB + 1
	}
	jSub = 0
	for {
		if !(jSub < (*TExprList)(unsafe.Pointer(pSubOB)).FnExpr && iOB < (*TExprList)(unsafe.Pointer(pOrderBy)).FnExpr) {
			break
		}
		if libc.Int32FromUint16(*(*Tu16)(unsafe.Pointer(pSubOB + 8 + uintptr(jSub)*20 + 16))) == 0 {
			break
		}
		pOBExpr = (*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(iOB)*20))).FpExpr
		if libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pOBExpr)).Fop) != int32(TK_COLUMN) && libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pOBExpr)).Fop) != int32(TK_AGG_COLUMN) {
			break
		}
		if (*TExpr)(unsafe.Pointer(pOBExpr)).FiTable != iCur {
			break
		}
		if int32((*TExpr)(unsafe.Pointer(pOBExpr)).FiColumn) != libc.Int32FromUint16(*(*Tu16)(unsafe.Pointer(pSubOB + 8 + uintptr(jSub)*20 + 16)))-int32(1) {
			break
		}
		if libc.Int32FromUint16((*TWhereInfo)(unsafe.Pointer(pWInfo)).FwctrlFlags)&int32(WHERE_GROUPBY) == 0 {
			sfOB = (*(*TExprList_item)(unsafe.Pointer(pOrderBy + 8 + uintptr(iOB)*20))).Ffg.FsortFlags /* sortFlags for iOB */
			sfSub = (*(*TExprList_item)(unsafe.Pointer(pSubOB + 8 + uintptr(jSub)*20))).Ffg.FsortFlags /* sortFlags for jSub */
			if libc.Int32FromUint8(sfSub)&int32(KEYINFO_ORDER_BIGNULL) != libc.Int32FromUint8(sfOB)&int32(KEYINFO_ORDER_BIGNULL) {
				break
			}
			revIdx = libc.Uint8FromInt32(libc.Int32FromUint8(sfSub) & int32(KEYINFO_ORDER_DESC))
			if jSub > 0 {
				if libc.Int32FromUint8(rev)^libc.Int32FromUint8(revIdx) != libc.Int32FromUint8(sfOB)&int32(KEYINFO_ORDER_DESC) {
					break
				}
			} else {
				rev = libc.Uint8FromInt32(libc.Int32FromUint8(revIdx) ^ libc.Int32FromUint8(sfOB)&int32(KEYINFO_ORDER_DESC))
				if rev != 0 {
					if (*TWhereLoop)(unsafe.Pointer(pLoop)).FwsFlags&uint32(WHERE_COROUTINE) != uint32(0) {
						/* Cannot run a co-routine in reverse order */
						break
					}
					**(**TBitmask)(__ccgo_up(pRevMask)) |= libc.Uint64FromInt32(1) << iLoop
				}
			}
		}
		**(**TBitmask)(__ccgo_up(pOBSat)) |= libc.Uint64FromInt32(1) << iOB
		goto _2
	_2:
		;
		jSub = jSub + 1
		iOB = iOB + 1
	}
	return libc.BoolInt32(jSub > 0)
}

// C documentation
//
//	/* Check to see if a partial index with pPartIndexWhere can be used
//	** in the current query.  Return true if it can be and false if not.
//	*/
func _whereUsablePartialIndex(tls *libc.TLS, iTab int32, jointype Tu8, pWC uintptr, pWhere uintptr) (r int32) {
	var i int32
	var pExpr, pParse, pTerm uintptr
	_, _, _, _ = i, pExpr, pParse, pTerm
	if libc.Int32FromUint8(jointype)&int32(JT_LTORJ) != 0 {
		return 0
	}
	pParse = (*TWhereInfo)(unsafe.Pointer((*TWhereClause)(unsafe.Pointer(pWC)).FpWInfo)).FpParse
	for libc.Int32FromUint8((*TExpr)(unsafe.Pointer(pWhere)).Fop) == int32(TK_AND) {
		if !(_whereUsablePartialIndex(tls, iTab, jointype, pWC, (*TExpr)(unsafe.Pointer(pWhere)).FpLeft) != 0) {
			return 0
		}
		pWhere = (*TExpr)(unsafe.Pointer(pWhere)).FpRight
	}
	i = 0
	pTerm = (*TWhereClause)(unsafe.Pointer(pWC)).Fa
	for {
		if !(i < (*TWhereClause)(unsafe.Pointer(pWC)).FnTerm) {
			break
		}
		pExpr = (*TWhereTerm)(unsafe.Pointer(pTerm)).FpExpr
		if (!((*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != libc.Uint32FromInt32(0)) || *(*int32)(unsafe.Pointer(pExpr + 36)) == iTab) && (libc.Int32FromUint8(jointype)&int32(JT_OUTER) == 0 || (*TExpr)(unsafe.Pointer(pExpr)).Fflags&libc.Uint32FromInt32(libc.Int32FromInt32(EP_OuterON)) != uint32(0)) && _sqlite3ExprImpliesExpr(tls, pParse, pExpr, pWhere, iTab) != 0 && !(_sqlite3ExprImpliesExpr(tls, pParse, pExpr, pWhere, -int32(1)) != 0) && libc.Int32FromUint16((*TWhereTerm)(unsafe.Pointer(pTerm)).FwtFlags)&int32(TERM_VNULL) == 0 {
			return int32(1)
		}
		goto _1
	_1:
		;
		i = i + 1
		pTerm += 48
	}
	return 0
}

// C documentation
//
//	/*
//	** Generate VM code to invoke either xStep() (if bInverse is 0) or
//	** xInverse (if bInverse is non-zero) for each window function in the
//	** linked list starting at pMWin. Or, for built-in window functions
//	** that do not use the standard function API, generate the required
//	** inline VM code.
//	**
//	** If argument csr is greater than or equal to 0, then argument reg is
//	** the first register in an array of registers guaranteed to be large
//	** enough to hold the array of arguments for each function. In this case
//	** the arguments are extracted from the current row of csr into the
//	** array of registers before invoking OP_AggStep or OP_AggInverse
//	**
//	** Or, if csr is less than zero, then the array of registers at reg is
//	** already populated with all columns from the current row of the sub-query.
//	**
//	** If argument regPartSize is non-zero, then it is a register containing the
//	** number of rows in the current partition.
//	*/
func _windowAggStep(tls *libc.TLS, p uintptr, pMWin uintptr, csr int32, bInverse int32, reg int32) {
	var addrIf, addrIsNull, i, iEnd, iOp, nArg, regArg, regTmp, v2 int32
	var pColl, pFunc, pOp, pParse, pWin, v uintptr
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = addrIf, addrIsNull, i, iEnd, iOp, nArg, pColl, pFunc, pOp, pParse, pWin, regArg, regTmp, v, v2
	pParse = (*TWindowCodeArg)(unsafe.Pointer(p)).FpParse
	v = _sqlite3GetVdbe(tls, pParse)
	pWin = pMWin
	for {
		if !(pWin != 0) {
			break
		}
		pFunc = (*TWindow)(unsafe.Pointer(pWin)).FpWFunc
		if (*TWindow)(unsafe.Pointer(pWin)).FbExprArgs != 0 {
			v2 = 0
		} else {
			v2 = _windowArgCount(tls, pWin)
		}
		nArg = v2
		addrIf = 0
		/* All OVER clauses in the same window function aggregate step must
		 ** be the same. */
		i = 0
		for {
			if !(i < nArg) {
				break
			}
			if i != int32(1) || (*TFuncDef)(unsafe.Pointer(pFunc)).FzName != uintptr(unsafe.Pointer(&_nth_valueName)) {
				_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), csr, (*TWindow)(unsafe.Pointer(pWin)).FiArgCol+i, reg+i)
			} else {
				_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), (*TWindow)(unsafe.Pointer(pMWin)).FiEphCsr, (*TWindow)(unsafe.Pointer(pWin)).FiArgCol+i, reg+i)
			}
			goto _3
		_3:
			;
			i = i + 1
		}
		regArg = reg
		if (*TWindow)(unsafe.Pointer(pWin)).FpFilter != 0 {
			regTmp = _sqlite3GetTempReg(tls, pParse)
			_sqlite3VdbeAddOp3(tls, v, int32(OP_Column), csr, (*TWindow)(unsafe.Pointer(pWin)).FiArgCol+nArg, regTmp)
			addrIf = _sqlite3VdbeAddOp3(tls, v, int32(OP_IfNot), regTmp, 0, int32(1))
			_sqlite3ReleaseTempReg(tls, pParse, regTmp)
		}
		if (*TWindow)(unsafe.Pointer(pMWin)).FregStartRowid == 0 && (*TFuncDef)(unsafe.Pointer(pFunc)).FfuncFlags&uint32(SQLITE_FUNC_MINMAX) != 0 && libc.Int32FromUint8((*TWindow)(unsafe.Pointer(pWin)).FeStart) != int32(TK_UNBOUNDED) {
			addrIsNull = _sqlite3VdbeAddOp1(tls, v, int32(OP_IsNull), regArg)
			if bInverse == 0 {
				_sqlite3VdbeAddOp2(tls, v, int32(OP_AddImm), (*TWindow)(unsafe.Pointer(pWin)).FregApp+int32(1), int32(1))
				_sqlite3VdbeAddOp2(tls, v, int32(OP_SCopy), regArg, (*TWindow)(unsafe.Pointer(pWin)).FregApp)
				_sqlite3VdbeAddOp3(tls, v, int32(OP_MakeRecord), (*TWindow)(unsafe.Pointer(pWin)).FregApp, int32(2), (*TWindow)(unsafe.Pointer(pWin)).FregApp+int32(2))
				_sqlite3VdbeAddOp2(tls, v, int32(OP_IdxInsert), (*TWindow)(unsafe.Pointer(pWin)).FcsrApp, (*TWindow)(unsafe.Pointer(pWin)).FregApp+int32(2))
			} else {
				_sqlite3VdbeAddOp4Int(tls, v, int32(OP_SeekGE), (*TWindow)(unsafe.Pointer(pWin)).FcsrApp, 0, regArg, int32(1))
				_sqlite3VdbeAddOp1(tls, v, int32(OP_Delete), (*TWindow)(unsafe.Pointer(pWin)).FcsrApp)
				_sqlite3VdbeJumpHere(tls, v, _sqlite3VdbeCurrentAddr(tls, v)-int32(2))
			}
			_sqlite3VdbeJumpHere(tls, v, addrIsNull)
		} else {
			if (*TWindow)(unsafe.Pointer(pWin)).FregApp != 0 {
				_sqlite3VdbeAddOp2(tls, v, int32(OP_AddImm), (*TWindow)(unsafe.Pointer(pWin)).FregApp+int32(1)-bInverse, int32(1))
			} else {
				if (*TFuncDef)(unsafe.Pointer(pFunc)).FxSFunc != __ccgo_fp(_noopStepFunc) {
					if (*TWindow)(unsafe.Pointer(pWin)).FbExprArgs != 0 {
						iOp = _sqlite3VdbeCurrentAddr(tls, v)
						nArg = (*TExprList)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer((*TWindow)(unsafe.Pointer(pWin)).FpOwner + 20)))).FnExpr
						regArg = _sqlite3GetTempRange(tls, pParse, nArg)
						_sqlite3ExprCodeExprList(tls, pParse, *(*uintptr)(unsafe.Pointer((*TWindow)(unsafe.Pointer(pWin)).FpOwner + 20)), regArg, 0, uint8(0))
						iEnd = _sqlite3VdbeCurrentAddr(tls, v)
						for {
							if !(iOp < iEnd) {
								break
							}
							pOp = _sqlite3VdbeGetOp(tls, v, iOp)
							if libc.Int32FromUint8((*TVdbeOp)(unsafe.Pointer(pOp)).Fopcode) == int32(OP_Column) && (*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 == (*TWindow)(unsafe.Pointer(pMWin)).FiEphCsr {
								(*TVdbeOp)(unsafe.Pointer(pOp)).Fp1 = csr
							}
							goto _4
						_4:
							;
							iOp = iOp + 1
						}
					}
					if (*TFuncDef)(unsafe.Pointer(pFunc)).FfuncFlags&uint32(SQLITE_FUNC_NEEDCOLL) != 0 {
						pColl = _sqlite3ExprNNCollSeq(tls, pParse, (*(*TExprList_item)(unsafe.Pointer(*(*uintptr)(unsafe.Pointer((*TWindow)(unsafe.Pointer(pWin)).FpOwner + 20)) + 8))).FpExpr)
						_sqlite3VdbeAddOp4(tls, v, int32(OP_CollSeq), 0, 0, 0, pColl, -int32(2))
					}
					if bInverse != 0 {
						v2 = int32(OP_AggInverse)
					} else {
						v2 = int32(OP_AggStep)
					}
					_sqlite3VdbeAddOp3(tls, v, v2, bInverse, regArg, (*TWindow)(unsafe.Pointer(pWin)).FregAccum)
					_sqlite3VdbeAppendP4(tls, v, pFunc, -int32(8))
					_sqlite3VdbeChangeP5(tls, v, libc.Uint16FromInt32(nArg))
					if (*TWindow)(unsafe.Pointer(pWin)).FbExprArgs != 0 {
						_sqlite3ReleaseTempRange(tls, pParse, regArg, nArg)
					}
				}
			}
		}
		if addrIf != 0 {
			_sqlite3VdbeJumpHere(tls, v, addrIf)
		}
		goto _1
	_1:
		;
		pWin = (*TWindow)(unsafe.Pointer(pWin)).FpNextWin
	}
}

/*
** Values that may be passed as the second argument to windowCodeOp().
 */

// C documentation
//
//	/*
//	** Check to see if index pSrc is compatible as a source of data
//	** for index pDest in an insert transfer optimization.  The rules
//	** for a compatible index:
//	**
//	**    *   The index is over the same set of columns
//	**    *   The same DESC and ASC markings occurs on all columns
//	**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
//	**    *   The same collating sequence on each column
//	**    *   The index has the exact same WHERE clause
//	*/
func _xferCompatibleIndex(tls *libc.TLS, pDest uintptr, pSrc uintptr) (r int32) {
	var i int32
	_ = i
	if libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pDest)).FnKeyCol) != libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pSrc)).FnKeyCol) || libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pDest)).FnColumn) != libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pSrc)).FnColumn) {
		return 0 /* Different number of columns */
	}
	if libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pDest)).FonError) != libc.Int32FromUint8((*TIndex)(unsafe.Pointer(pSrc)).FonError) {
		return 0 /* Different conflict resolution strategies */
	}
	i = 0
	for {
		if !(i < libc.Int32FromUint16((*TIndex)(unsafe.Pointer(pSrc)).FnKeyCol)) {
			break
		}
		if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pSrc)).FaiColumn + uintptr(i)*2))) != int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pDest)).FaiColumn + uintptr(i)*2))) {
			return 0 /* Different columns indexed */
		}
		if int32(**(**Ti16)(__ccgo_up((*TIndex)(unsafe.Pointer(pSrc)).FaiColumn + uintptr(i)*2))) == -int32(2) {
			if _sqlite3ExprCompare(tls, uintptr(0), (*(*TExprList_item)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pSrc)).FaColExpr + 8 + uintptr(i)*20))).FpExpr, (*(*TExprList_item)(unsafe.Pointer((*TIndex)(unsafe.Pointer(pDest)).FaColExpr + 8 + uintptr(i)*20))).FpExpr, -int32(1)) != 0 {
				return 0 /* Different expressions in the index */
			}
		}
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TIndex)(unsafe.Pointer(pSrc)).FaSortOrder + uintptr(i)))) != libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TIndex)(unsafe.Pointer(pDest)).FaSortOrder + uintptr(i)))) {
			return 0 /* Different sort orders */
		}
		if Xsqlite3_stricmp(tls, **(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pSrc)).FazColl + uintptr(i)*4)), **(**uintptr)(__ccgo_up((*TIndex)(unsafe.Pointer(pDest)).FazColl + uintptr(i)*4))) != 0 {
			return 0 /* Different collating sequences */
		}
		goto _1
	_1:
		;
		i = i + 1
	}
	if _sqlite3ExprCompare(tls, uintptr(0), (*TIndex)(unsafe.Pointer(pSrc)).FpPartIdxWhere, (*TIndex)(unsafe.Pointer(pDest)).FpPartIdxWhere, -int32(1)) != 0 {
		return 0 /* Different WHERE clauses */
	}
	/* If no test above fails then the indices must be compatible */
	return int32(1)
}

// C documentation
//
//	/*
//	** Try to increase the size of the parser stack.  Return the number
//	** of errors.  Return 0 on success.
//	*/
func _yyGrowStack(tls *libc.TLS, p uintptr) (r int32) {
	var idx, nLimit, newSize, oldSize int32
	var pNew uintptr
	_, _, _, _, _ = idx, nLimit, newSize, oldSize, pNew
	oldSize = int32(1) + (int32((*TyyParser)(unsafe.Pointer(p)).FyystackEnd)-int32((*TyyParser)(unsafe.Pointer(p)).Fyystack))/12
	nLimit = _parserStackSizeLimit(tls, (*TyyParser)(unsafe.Pointer(p)).FpParse)
	newSize = oldSize*int32(2) + int32(100)
	if newSize > nLimit {
		newSize = nLimit
		if newSize <= oldSize {
			return int32(1)
		}
	}
	idx = (int32((*TyyParser)(unsafe.Pointer(p)).Fyytos) - int32((*TyyParser)(unsafe.Pointer(p)).Fyystack)) / 12
	if (*TyyParser)(unsafe.Pointer(p)).Fyystack == p+16 {
		pNew = _parserStackRealloc(tls, uintptr(0), uint64(libc.Uint32FromInt32(newSize)*uint32(12)), (*TyyParser)(unsafe.Pointer(p)).FpParse)
		if pNew == uintptr(0) {
			return int32(1)
		}
		libc.Xmemcpy(tls, pNew, (*TyyParser)(unsafe.Pointer(p)).Fyystack, libc.Uint32FromInt32(oldSize)*uint32(12))
	} else {
		pNew = _parserStackRealloc(tls, (*TyyParser)(unsafe.Pointer(p)).Fyystack, uint64(libc.Uint32FromInt32(newSize)*uint32(12)), (*TyyParser)(unsafe.Pointer(p)).FpParse)
		if pNew == uintptr(0) {
			return int32(1)
		}
	}
	(*TyyParser)(unsafe.Pointer(p)).Fyystack = pNew
	(*TyyParser)(unsafe.Pointer(p)).Fyytos = (*TyyParser)(unsafe.Pointer(p)).Fyystack + uintptr(idx)*12
	(*TyyParser)(unsafe.Pointer(p)).FyystackEnd = (*TyyParser)(unsafe.Pointer(p)).Fyystack + uintptr(newSize-int32(1))*12
	return 0
}

/* Datatype of the argument to the memory allocated passed as the
** second argument to sqlite3ParserAlloc() below.  This can be changed by
** putting an appropriate #define in the %include section of the input
** grammar.
 */

// C documentation
//
//	/*
//	** Perform a shift action.
//	*/
func _yy_shift(tls *libc.TLS, yypParser uintptr, yyNewState uint16, yyMajor uint16, yyMinor TToken) {
	var yytos uintptr
	_ = yytos
	(*TyyParser)(unsafe.Pointer(yypParser)).Fyytos += 12
	yytos = (*TyyParser)(unsafe.Pointer(yypParser)).Fyytos
	if yytos > (*TyyParser)(unsafe.Pointer(yypParser)).FyystackEnd {
		if _yyGrowStack(tls, yypParser) != 0 {
			(*TyyParser)(unsafe.Pointer(yypParser)).Fyytos -= 12
			_yyStackOverflow(tls, yypParser)
			return
		}
		yytos = (*TyyParser)(unsafe.Pointer(yypParser)).Fyytos
	}
	if libc.Int32FromUint16(yyNewState) > int32(YY_MAX_SHIFT) {
		yyNewState = libc.Uint16FromInt32(int32(yyNewState) + (libc.Int32FromInt32(YY_MIN_REDUCE) - libc.Int32FromInt32(YY_MIN_SHIFTREDUCE)))
	}
	(*TyyStackEntry)(unsafe.Pointer(yytos)).Fstateno = yyNewState
	(*TyyStackEntry)(unsafe.Pointer(yytos)).Fmajor = yyMajor
	*(*TToken)(unsafe.Pointer(yytos + 4)) = yyMinor
}

func init() {
	p := unsafe.Pointer(&_dotlockIoMethods)
	*(*uintptr)(unsafe.Add(p, 4)) = __ccgo_fp(_dotlockClose)
	*(*uintptr)(unsafe.Add(p, 8)) = __ccgo_fp(_unixRead)
	*(*uintptr)(unsafe.Add(p, 12)) = __ccgo_fp(_unixWrite)
	*(*uintptr)(unsafe.Add(p, 16)) = __ccgo_fp(_unixTruncate)
	*(*uintptr)(unsafe.Add(p, 20)) = __ccgo_fp(_unixSync)
	*(*uintptr)(unsafe.Add(p, 24)) = __ccgo_fp(_unixFileSize)
	*(*uintptr)(unsafe.Add(p, 28)) = __ccgo_fp(_dotlockLock)
	*(*uintptr)(unsafe.Add(p, 32)) = __ccgo_fp(_dotlockUnlock)
	*(*uintptr)(unsafe.Add(p, 36)) = __ccgo_fp(_dotlockCheckReservedLock)
	*(*uintptr)(unsafe.Add(p, 40)) = __ccgo_fp(_unixFileControl)
	*(*uintptr)(unsafe.Add(p, 44)) = __ccgo_fp(_unixSectorSize)
	*(*uintptr)(unsafe.Add(p, 48)) = __ccgo_fp(_unixDeviceCharacteristics)
	*(*uintptr)(unsafe.Add(p, 56)) = __ccgo_fp(_unixShmLock)
	*(*uintptr)(unsafe.Add(p, 60)) = __ccgo_fp(_unixShmBarrier)
	*(*uintptr)(unsafe.Add(p, 64)) = __ccgo_fp(_unixShmUnmap)
	*(*uintptr)(unsafe.Add(p, 68)) = __ccgo_fp(_unixFetch)
	*(*uintptr)(unsafe.Add(p, 72)) = __ccgo_fp(_unixUnfetch)
}

func init() {
	p := unsafe.Pointer(&_posixIoMethods)
	*(*uintptr)(unsafe.Add(p, 4)) = __ccgo_fp(_unixClose)
	*(*uintptr)(unsafe.Add(p, 8)) = __ccgo_fp(_unixRead)
	*(*uintptr)(unsafe.Add(p, 12)) = __ccgo_fp(_unixWrite)
	*(*uintptr)(unsafe.Add(p, 16)) = __ccgo_fp(_unixTruncate)
	*(*uintptr)(unsafe.Add(p, 20)) = __ccgo_fp(_unixSync)
	*(*uintptr)(unsafe.Add(p, 24)) = __ccgo_fp(_unixFileSize)
	*(*uintptr)(unsafe.Add(p, 28)) = __ccgo_fp(_unixLock)
	*(*uintptr)(unsafe.Add(p, 32)) = __ccgo_fp(_unixUnlock)
	*(*uintptr)(unsafe.Add(p, 36)) = __ccgo_fp(_unixCheckReservedLock)
	*(*uintptr)(unsafe.Add(p, 40)) = __ccgo_fp(_unixFileControl)
	*(*uintptr)(unsafe.Add(p, 44)) = __ccgo_fp(_unixSectorSize)
	*(*uintptr)(unsafe.Add(p, 48)) = __ccgo_fp(_unixDeviceCharacteristics)
	*(*uintptr)(unsafe.Add(p, 52)) = __ccgo_fp(_unixShmMap)
	*(*uintptr)(unsafe.Add(p, 56)) = __ccgo_fp(_unixShmLock)
	*(*uintptr)(unsafe.Add(p, 60)) = __ccgo_fp(_unixShmBarrier)
	*(*uintptr)(unsafe.Add(p, 64)) = __ccgo_fp(_unixShmUnmap)
	*(*uintptr)(unsafe.Add(p, 68)) = __ccgo_fp(_unixFetch)
	*(*uintptr)(unsafe.Add(p, 72)) = __ccgo_fp(_unixUnfetch)
}

func init() {
	p := unsafe.Pointer(&_nolockIoMethods)
	*(*uintptr)(unsafe.Add(p, 4)) = __ccgo_fp(_nolockClose)
	*(*uintptr)(unsafe.Add(p, 8)) = __ccgo_fp(_unixRead)
	*(*uintptr)(unsafe.Add(p, 12)) = __ccgo_fp(_unixWrite)
	*(*uintptr)(unsafe.Add(p, 16)) = __ccgo_fp(_unixTruncate)
	*(*uintptr)(unsafe.Add(p, 20)) = __ccgo_fp(_unixSync)
	*(*uintptr)(unsafe.Add(p, 24)) = __ccgo_fp(_unixFileSize)
	*(*uintptr)(unsafe.Add(p, 28)) = __ccgo_fp(_nolockLock)
	*(*uintptr)(unsafe.Add(p, 32)) = __ccgo_fp(_nolockUnlock)
	*(*uintptr)(unsafe.Add(p, 36)) = __ccgo_fp(_nolockCheckReservedLock)
	*(*uintptr)(unsafe.Add(p, 40)) = __ccgo_fp(_unixFileControl)
	*(*uintptr)(unsafe.Add(p, 44)) = __ccgo_fp(_unixSectorSize)
	*(*uintptr)(unsafe.Add(p, 48)) = __ccgo_fp(_unixDeviceCharacteristics)
	*(*uintptr)(unsafe.Add(p, 56)) = __ccgo_fp(_unixShmLock)
	*(*uintptr)(unsafe.Add(p, 60)) = __ccgo_fp(_unixShmBarrier)
	*(*uintptr)(unsafe.Add(p, 64)) = __ccgo_fp(_unixShmUnmap)
	*(*uintptr)(unsafe.Add(p, 68)) = __ccgo_fp(_unixFetch)
	*(*uintptr)(unsafe.Add(p, 72)) = __ccgo_fp(_unixUnfetch)
}

func init() {
	p := unsafe.Pointer(&_aVfs)
	*(*uintptr)(unsafe.Add(p, 20)) = uintptr(unsafe.Pointer(&_posixIoFinder))
	*(*uintptr)(unsafe.Add(p, 24)) = __ccgo_fp(_unixOpen)
	*(*uintptr)(unsafe.Add(p, 28)) = __ccgo_fp(_unixDelete)
	*(*uintptr)(unsafe.Add(p, 32)) = __ccgo_fp(_unixAccess)
	*(*uintptr)(unsafe.Add(p, 36)) = __ccgo_fp(_unixFullPathname)
	*(*uintptr)(unsafe.Add(p, 40)) = __ccgo_fp(_unixDlOpen)
	*(*uintptr)(unsafe.Add(p, 44)) = __ccgo_fp(_unixDlError)
	*(*uintptr)(unsafe.Add(p, 48)) = __ccgo_fp(_unixDlSym)
	*(*uintptr)(unsafe.Add(p, 52)) = __ccgo_fp(_unixDlClose)
	*(*uintptr)(unsafe.Add(p, 56)) = __ccgo_fp(_unixRandomness)
	*(*uintptr)(unsafe.Add(p, 60)) = __ccgo_fp(_unixSleep)
	*(*uintptr)(unsafe.Add(p, 64)) = __ccgo_fp(_unixCurrentTime)
	*(*uintptr)(unsafe.Add(p, 68)) = __ccgo_fp(_unixGetLastError)
	*(*uintptr)(unsafe.Add(p, 72)) = __ccgo_fp(_unixCurrentTimeInt64)
	*(*uintptr)(unsafe.Add(p, 76)) = __ccgo_fp(_unixSetSystemCall)
	*(*uintptr)(unsafe.Add(p, 80)) = __ccgo_fp(_unixGetSystemCall)
	*(*uintptr)(unsafe.Add(p, 84)) = __ccgo_fp(_unixNextSystemCall)
	*(*uintptr)(unsafe.Add(p, 108)) = uintptr(unsafe.Pointer(&_nolockIoFinder))
	*(*uintptr)(unsafe.Add(p, 112)) = __ccgo_fp(_unixOpen)
	*(*uintptr)(unsafe.Add(p, 116)) = __ccgo_fp(_unixDelete)
	*(*uintptr)(unsafe.Add(p, 120)) = __ccgo_fp(_unixAccess)
	*(*uintptr)(unsafe.Add(p, 124)) = __ccgo_fp(_unixFullPathname)
	*(*uintptr)(unsafe.Add(p, 128)) = __ccgo_fp(_unixDlOpen)
	*(*uintptr)(unsafe.Add(p, 132)) = __ccgo_fp(_unixDlError)
	*(*uintptr)(unsafe.Add(p, 136)) = __ccgo_fp(_unixDlSym)
	*(*uintptr)(unsafe.Add(p, 140)) = __ccgo_fp(_unixDlClose)
	*(*uintptr)(unsafe.Add(p, 144)) = __ccgo_fp(_unixRandomness)
	*(*uintptr)(unsafe.Add(p, 148)) = __ccgo_fp(_unixSleep)
	*(*uintptr)(unsafe.Add(p, 152)) = __ccgo_fp(_unixCurrentTime)
	*(*uintptr)(unsafe.Add(p, 156)) = __ccgo_fp(_unixGetLastError)
	*(*uintptr)(unsafe.Add(p, 160)) = __ccgo_fp(_unixCurrentTimeInt64)
	*(*uintptr)(unsafe.Add(p, 164)) = __ccgo_fp(_unixSetSystemCall)
	*(*uintptr)(unsafe.Add(p, 168)) = __ccgo_fp(_unixGetSystemCall)
	*(*uintptr)(unsafe.Add(p, 172)) = __ccgo_fp(_unixNextSystemCall)
	*(*uintptr)(unsafe.Add(p, 196)) = uintptr(unsafe.Pointer(&_dotlockIoFinder))
	*(*uintptr)(unsafe.Add(p, 200)) = __ccgo_fp(_unixOpen)
	*(*uintptr)(unsafe.Add(p, 204)) = __ccgo_fp(_unixDelete)
	*(*uintptr)(unsafe.Add(p, 208)) = __ccgo_fp(_unixAccess)
	*(*uintptr)(unsafe.Add(p, 212)) = __ccgo_fp(_unixFullPathname)
	*(*uintptr)(unsafe.Add(p, 216)) = __ccgo_fp(_unixDlOpen)
	*(*uintptr)(unsafe.Add(p, 220)) = __ccgo_fp(_unixDlError)
	*(*uintptr)(unsafe.Add(p, 224)) = __ccgo_fp(_unixDlSym)
	*(*uintptr)(unsafe.Add(p, 228)) = __ccgo_fp(_unixDlClose)
	*(*uintptr)(unsafe.Add(p, 232)) = __ccgo_fp(_unixRandomness)
	*(*uintptr)(unsafe.Add(p, 236)) = __ccgo_fp(_unixSleep)
	*(*uintptr)(unsafe.Add(p, 240)) = __ccgo_fp(_unixCurrentTime)
	*(*uintptr)(unsafe.Add(p, 244)) = __ccgo_fp(_unixGetLastError)
	*(*uintptr)(unsafe.Add(p, 248)) = __ccgo_fp(_unixCurrentTimeInt64)
	*(*uintptr)(unsafe.Add(p, 252)) = __ccgo_fp(_unixSetSystemCall)
	*(*uintptr)(unsafe.Add(p, 256)) = __ccgo_fp(_unixGetSystemCall)
	*(*uintptr)(unsafe.Add(p, 260)) = __ccgo_fp(_unixNextSystemCall)
	*(*uintptr)(unsafe.Add(p, 284)) = uintptr(unsafe.Pointer(&_posixIoFinder))
	*(*uintptr)(unsafe.Add(p, 288)) = __ccgo_fp(_unixOpen)
	*(*uintptr)(unsafe.Add(p, 292)) = __ccgo_fp(_unixDelete)
	*(*uintptr)(unsafe.Add(p, 296)) = __ccgo_fp(_unixAccess)
	*(*uintptr)(unsafe.Add(p, 300)) = __ccgo_fp(_unixFullPathname)
	*(*uintptr)(unsafe.Add(p, 304)) = __ccgo_fp(_unixDlOpen)
	*(*uintptr)(unsafe.Add(p, 308)) = __ccgo_fp(_unixDlError)
	*(*uintptr)(unsafe.Add(p, 312)) = __ccgo_fp(_unixDlSym)
	*(*uintptr)(unsafe.Add(p, 316)) = __ccgo_fp(_unixDlClose)
	*(*uintptr)(unsafe.Add(p, 320)) = __ccgo_fp(_unixRandomness)
	*(*uintptr)(unsafe.Add(p, 324)) = __ccgo_fp(_unixSleep)
	*(*uintptr)(unsafe.Add(p, 328)) = __ccgo_fp(_unixCurrentTime)
	*(*uintptr)(unsafe.Add(p, 332)) = __ccgo_fp(_unixGetLastError)
	*(*uintptr)(unsafe.Add(p, 336)) = __ccgo_fp(_unixCurrentTimeInt64)
	*(*uintptr)(unsafe.Add(p, 340)) = __ccgo_fp(_unixSetSystemCall)
	*(*uintptr)(unsafe.Add(p, 344)) = __ccgo_fp(_unixGetSystemCall)
	*(*uintptr)(unsafe.Add(p, 348)) = __ccgo_fp(_unixNextSystemCall)
}
