package world.respect.datalayer.db.school.daos

import androidx.collection.LongSparseArray
import androidx.paging.PagingSource
import androidx.room.EntityInsertAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomRawQuery
import androidx.room.coroutines.createFlow
import androidx.room.paging.LimitOffsetPagingSource
import androidx.room.util.appendPlaceholders
import androidx.room.util.getColumnIndex
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.performSuspending
import androidx.room.util.recursiveFetchLongSparseArray
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteStatement
import javax.`annotation`.processing.Generated
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.MutableList
import kotlin.collections.mutableListOf
import kotlin.reflect.KClass
import kotlin.text.StringBuilder
import kotlin.time.Instant
import kotlinx.coroutines.flow.Flow
import world.respect.datalayer.db.school.SchoolTypeConverters
import world.respect.datalayer.db.school.entities.ClassEntity
import world.respect.datalayer.db.school.entities.ClassEntityWithPermissions
import world.respect.datalayer.db.school.entities.ClassPermissionEntity
import world.respect.datalayer.db.school.entities.LastModifiedAndPermission
import world.respect.datalayer.db.shared.SharedConverters
import world.respect.datalayer.school.model.EnrollmentRoleEnum
import world.respect.datalayer.school.model.StatusEnum

@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION", "REDUNDANT_PROJECTION", "REMOVAL"])
public class ClassEntityDao_Impl(
  __db: RoomDatabase,
) : ClassEntityDao {
  private val __db: RoomDatabase

  private val __insertAdapterOfClassEntity: EntityInsertAdapter<ClassEntity>

  private val __schoolTypeConverters: SchoolTypeConverters = SchoolTypeConverters()

  private val __sharedConverters: SharedConverters = SharedConverters()
  init {
    this.__db = __db
    this.__insertAdapterOfClassEntity = object : EntityInsertAdapter<ClassEntity>() {
      protected override fun createQuery(): String = "INSERT OR REPLACE INTO `ClassEntity` (`cGuid`,`cGuidHash`,`cTitle`,`cStatus`,`cDescription`,`cLastModified`,`cStored`,`cTeacherInviteGuid`,`cStudentInviteGuid`) VALUES (?,?,?,?,?,?,?,?,?)"

      protected override fun bind(statement: SQLiteStatement, entity: ClassEntity) {
        statement.bindText(1, entity.cGuid)
        statement.bindLong(2, entity.cGuidHash)
        statement.bindText(3, entity.cTitle)
        val _tmp: Int = __schoolTypeConverters.fromStatusEnum(entity.cStatus)
        statement.bindLong(4, _tmp.toLong())
        val _tmpCDescription: String? = entity.cDescription
        if (_tmpCDescription == null) {
          statement.bindNull(5)
        } else {
          statement.bindText(5, _tmpCDescription)
        }
        val _tmp_1: Long? = __sharedConverters.fromInstant(entity.cLastModified)
        if (_tmp_1 == null) {
          statement.bindNull(6)
        } else {
          statement.bindLong(6, _tmp_1)
        }
        val _tmp_2: Long? = __sharedConverters.fromInstant(entity.cStored)
        if (_tmp_2 == null) {
          statement.bindNull(7)
        } else {
          statement.bindLong(7, _tmp_2)
        }
        val _tmpCTeacherInviteGuid: String? = entity.cTeacherInviteGuid
        if (_tmpCTeacherInviteGuid == null) {
          statement.bindNull(8)
        } else {
          statement.bindText(8, _tmpCTeacherInviteGuid)
        }
        val _tmpCStudentInviteGuid: String? = entity.cStudentInviteGuid
        if (_tmpCStudentInviteGuid == null) {
          statement.bindNull(9)
        } else {
          statement.bindText(9, _tmpCStudentInviteGuid)
        }
      }
    }
  }

  public override suspend fun upsert(classEntity: ClassEntity): Unit = performSuspending(__db, false, true) { _connection ->
    __insertAdapterOfClassEntity.insert(_connection, classEntity)
  }

  public override fun findByGuidHashAsFlow(guidHash: Long): Flow<ClassEntityWithPermissions?> {
    val _sql: String = """
        |
        |        SELECT * 
        |         FROM ClassEntity
        |        WHERE ClassEntity.cGuidHash = ?
        |    
        """.trimMargin()
    return createFlow(__db, true, arrayOf("ClassPermissionEntity", "ClassEntity")) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindLong(_argIndex, guidHash)
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
        while (_stmt.step()) {
          val _tmpKey: Long
          _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
          if (!_collectionPermissions.containsKey(_tmpKey)) {
            _collectionPermissions.put(_tmpKey, mutableListOf())
          }
        }
        _stmt.reset()
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
        val _result: ClassEntityWithPermissions?
        if (_stmt.step()) {
          val _tmpClazz: ClassEntity
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
          val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
          val _tmpKey_1: Long
          _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
          _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
          _result = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun findByGuid(guidHash: Long): ClassEntityWithPermissions? {
    val _sql: String = """
        |
        |        SELECT * 
        |         FROM ClassEntity
        |        WHERE ClassEntity.cGuidHash = ?
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindLong(_argIndex, guidHash)
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
        while (_stmt.step()) {
          val _tmpKey: Long
          _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
          if (!_collectionPermissions.containsKey(_tmpKey)) {
            _collectionPermissions.put(_tmpKey, mutableListOf())
          }
        }
        _stmt.reset()
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
        val _result: ClassEntityWithPermissions?
        if (_stmt.step()) {
          val _tmpClazz: ClassEntity
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
          val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
          val _tmpKey_1: Long
          _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
          _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
          _result = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun getLastModifiedByGuid(uidNum: Long): Long? {
    val _sql: String = """
        |
        |        SELECT ClassEntity.cLastModified
        |          FROM ClassEntity
        |         WHERE ClassEntity.cGuidHash = ? 
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindLong(_argIndex, uidNum)
        val _result: Long?
        if (_stmt.step()) {
          if (_stmt.isNull(0)) {
            _result = null
          } else {
            _result = _stmt.getLong(0)
          }
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override fun listAsPagingSource(
    authenticatedPersonUidNum: Long,
    since: Long,
    guidHash: Long,
    code: String?,
    requiredPermission: Long,
  ): PagingSource<Int, ClassEntityWithPermissions> {
    val _sql: String = """
        |
        |        WITH 
        |            AuthenticatedPermissionPersonUids(uidNum) AS (
        |                SELECT ? AS uidNum
        |                UNION
        |                SELECT PersonRelatedPersonEntity.prpOtherPersonUidNum AS uidNum
        |                  FROM PersonRelatedPersonEntity
        |                 WHERE 16 IN 
        |                       (SELECT PersonRoleEntity.prRoleEnum
        |                          FROM PersonRoleEntity
        |                         WHERE PersonRoleEntity.prPersonGuidHash = ?)
        |                   AND PersonRelatedPersonEntity.prpPersonUidNum = ?)     
        |        ,
        |              
        |        AuthenticatedUserEnrollments AS (
        |             SELECT EnrollmentEntity.*
        |               FROM EnrollmentEntity
        |              WHERE EnrollmentEntity.ePersonUidNum IN
        |                    (SELECT AuthenticatedPermissionPersonUids.uidNum
        |                       FROM AuthenticatedPermissionPersonUids)
        |                AND EnrollmentEntity.eStatus = 1
        |        )
        |        
        |            
        |       SELECT ClassEntity.* 
        |         FROM ClassEntity
        |        WHERE ClassEntity.cStored > ? 
        |          AND (? = 0 OR ClassEntity.cGuidHash = ?)
        |          AND (
        |                EXISTS(
        |                   SELECT 1
        |                     FROM SchoolPermissionGrantEntity
        |                    WHERE SchoolPermissionGrantEntity.spgToRole IN (
        |                          SELECT PersonRoleEntity.prRoleEnum
        |                            FROM PersonRoleEntity
        |                           WHERE PersonRoleEntity.prPersonGuidHash IN
        |                                 (
        |            SELECT AuthenticatedPermissionPersonUids.uidNum
        |              FROM AuthenticatedPermissionPersonUids
        |        )) 
        |                      AND (SchoolPermissionGrantEntity.spgPermissions & ?) = ?
        |                      AND SchoolPermissionGrantEntity.spgStatusEnum = 1)
        |                OR EXISTS(
        |                   SELECT 1
        |                     FROM ClassPermissionEntity
        |                    WHERE ClassPermissionEntity.cpeClassUidNum = ClassEntity.cGuidHash
        |                      AND ClassPermissionEntity.cpeToEnrollmentRole IN 
        |                          (SELECT AuthenticatedUserEnrollments.eRole
        |                             FROM AuthenticatedUserEnrollments
        |                            WHERE AuthenticatedUserEnrollments.eClassUidNum = ClassEntity.cGuidHash)
        |                      AND (ClassPermissionEntity.cpePermissions & ?) = ?)
        |        )
        |          
        |          AND (? IS NULL 
        |                OR ClassEntity.cStudentInviteGuid = ?
        |                OR ClassEntity.cTeacherInviteGuid = ?)
        |     ORDER BY ClassEntity.cTitle
        |        
        """.trimMargin()
    val _rawQuery: RoomRawQuery = RoomRawQuery(_sql) { _stmt ->
      var _argIndex: Int = 1
      _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
      _argIndex = 2
      _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
      _argIndex = 3
      _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
      _argIndex = 4
      _stmt.bindLong(_argIndex, since)
      _argIndex = 5
      _stmt.bindLong(_argIndex, guidHash)
      _argIndex = 6
      _stmt.bindLong(_argIndex, guidHash)
      _argIndex = 7
      _stmt.bindLong(_argIndex, requiredPermission)
      _argIndex = 8
      _stmt.bindLong(_argIndex, requiredPermission)
      _argIndex = 9
      _stmt.bindLong(_argIndex, requiredPermission)
      _argIndex = 10
      _stmt.bindLong(_argIndex, requiredPermission)
      _argIndex = 11
      if (code == null) {
        _stmt.bindNull(_argIndex)
      } else {
        _stmt.bindText(_argIndex, code)
      }
      _argIndex = 12
      if (code == null) {
        _stmt.bindNull(_argIndex)
      } else {
        _stmt.bindText(_argIndex, code)
      }
      _argIndex = 13
      if (code == null) {
        _stmt.bindNull(_argIndex)
      } else {
        _stmt.bindText(_argIndex, code)
      }
    }
    return object : LimitOffsetPagingSource<ClassEntityWithPermissions>(_rawQuery, __db, "ClassPermissionEntity", "PersonRelatedPersonEntity", "PersonRoleEntity", "EnrollmentEntity", "ClassEntity", "SchoolPermissionGrantEntity") {
      protected override suspend fun convertRows(limitOffsetQuery: RoomRawQuery, itemCount: Int): List<ClassEntityWithPermissions> = performSuspending(__db, true, false) { _connection ->
        val _stmt: SQLiteStatement = _connection.prepare(limitOffsetQuery.sql)
        limitOffsetQuery.getBindingFunction().invoke(_stmt)
        try {
          val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
          val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
          val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
          val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
          val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
          val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
          val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
          val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
          val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
          val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
          while (_stmt.step()) {
            val _tmpKey: Long
            _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
            if (!_collectionPermissions.containsKey(_tmpKey)) {
              _collectionPermissions.put(_tmpKey, mutableListOf())
            }
          }
          _stmt.reset()
          __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
          val _result: MutableList<ClassEntityWithPermissions> = mutableListOf()
          while (_stmt.step()) {
            val _item: ClassEntityWithPermissions
            val _tmpClazz: ClassEntity
            val _tmpCGuid: String
            _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
            val _tmpCGuidHash: Long
            _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
            val _tmpCTitle: String
            _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
            val _tmpCStatus: StatusEnum
            val _tmp: Int
            _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
            _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
            val _tmpCDescription: String?
            if (_stmt.isNull(_columnIndexOfCDescription)) {
              _tmpCDescription = null
            } else {
              _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
            }
            val _tmpCLastModified: Instant
            val _tmp_1: Long?
            if (_stmt.isNull(_columnIndexOfCLastModified)) {
              _tmp_1 = null
            } else {
              _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
            }
            val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
            if (_tmp_2 == null) {
              error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
            } else {
              _tmpCLastModified = _tmp_2
            }
            val _tmpCStored: Instant
            val _tmp_3: Long?
            if (_stmt.isNull(_columnIndexOfCStored)) {
              _tmp_3 = null
            } else {
              _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
            }
            val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
            if (_tmp_4 == null) {
              error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
            } else {
              _tmpCStored = _tmp_4
            }
            val _tmpCTeacherInviteGuid: String?
            if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
              _tmpCTeacherInviteGuid = null
            } else {
              _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
            }
            val _tmpCStudentInviteGuid: String?
            if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
              _tmpCStudentInviteGuid = null
            } else {
              _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
            }
            _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
            val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
            val _tmpKey_1: Long
            _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
            _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
            _item = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
            _result.add(_item)
          }
          _result
        } finally {
          _stmt.close()
        }
      }
    }
  }

  public override suspend fun findByTeacherInviteCode(inviteCode: String): ClassEntity? {
    val _sql: String = """
        |
        |        SELECT * 
        |          FROM ClassEntity 
        |        WHERE cTeacherInviteGuid = ?
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindText(_argIndex, inviteCode)
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _result: ClassEntity?
        if (_stmt.step()) {
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _result = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun findByStudentInviteCode(inviteCode: String): ClassEntity? {
    val _sql: String = """
        |
        |        SELECT * 
        |          FROM ClassEntity 
        |        WHERE cStudentInviteGuid = ?
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindText(_argIndex, inviteCode)
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _result: ClassEntity?
        if (_stmt.step()) {
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _result = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun list(
    authenticatedPersonUidNum: Long,
    since: Long,
    guidHash: Long,
    code: String?,
    requiredPermission: Long,
  ): List<ClassEntityWithPermissions> {
    val _sql: String = """
        |
        |        WITH 
        |            AuthenticatedPermissionPersonUids(uidNum) AS (
        |                SELECT ? AS uidNum
        |                UNION
        |                SELECT PersonRelatedPersonEntity.prpOtherPersonUidNum AS uidNum
        |                  FROM PersonRelatedPersonEntity
        |                 WHERE 16 IN 
        |                       (SELECT PersonRoleEntity.prRoleEnum
        |                          FROM PersonRoleEntity
        |                         WHERE PersonRoleEntity.prPersonGuidHash = ?)
        |                   AND PersonRelatedPersonEntity.prpPersonUidNum = ?)     
        |        ,
        |              
        |        AuthenticatedUserEnrollments AS (
        |             SELECT EnrollmentEntity.*
        |               FROM EnrollmentEntity
        |              WHERE EnrollmentEntity.ePersonUidNum IN
        |                    (SELECT AuthenticatedPermissionPersonUids.uidNum
        |                       FROM AuthenticatedPermissionPersonUids)
        |                AND EnrollmentEntity.eStatus = 1
        |        )
        |        
        |            
        |       SELECT ClassEntity.* 
        |         FROM ClassEntity
        |        WHERE ClassEntity.cStored > ? 
        |          AND (? = 0 OR ClassEntity.cGuidHash = ?)
        |          AND (
        |                EXISTS(
        |                   SELECT 1
        |                     FROM SchoolPermissionGrantEntity
        |                    WHERE SchoolPermissionGrantEntity.spgToRole IN (
        |                          SELECT PersonRoleEntity.prRoleEnum
        |                            FROM PersonRoleEntity
        |                           WHERE PersonRoleEntity.prPersonGuidHash IN
        |                                 (
        |            SELECT AuthenticatedPermissionPersonUids.uidNum
        |              FROM AuthenticatedPermissionPersonUids
        |        )) 
        |                      AND (SchoolPermissionGrantEntity.spgPermissions & ?) = ?
        |                      AND SchoolPermissionGrantEntity.spgStatusEnum = 1)
        |                OR EXISTS(
        |                   SELECT 1
        |                     FROM ClassPermissionEntity
        |                    WHERE ClassPermissionEntity.cpeClassUidNum = ClassEntity.cGuidHash
        |                      AND ClassPermissionEntity.cpeToEnrollmentRole IN 
        |                          (SELECT AuthenticatedUserEnrollments.eRole
        |                             FROM AuthenticatedUserEnrollments
        |                            WHERE AuthenticatedUserEnrollments.eClassUidNum = ClassEntity.cGuidHash)
        |                      AND (ClassPermissionEntity.cpePermissions & ?) = ?)
        |        )
        |          
        |          AND (? IS NULL 
        |                OR ClassEntity.cStudentInviteGuid = ?
        |                OR ClassEntity.cTeacherInviteGuid = ?)
        |     ORDER BY ClassEntity.cTitle
        |        
        """.trimMargin()
    return performSuspending(__db, true, true) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 2
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 3
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 4
        _stmt.bindLong(_argIndex, since)
        _argIndex = 5
        _stmt.bindLong(_argIndex, guidHash)
        _argIndex = 6
        _stmt.bindLong(_argIndex, guidHash)
        _argIndex = 7
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 8
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 9
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 10
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 11
        if (code == null) {
          _stmt.bindNull(_argIndex)
        } else {
          _stmt.bindText(_argIndex, code)
        }
        _argIndex = 12
        if (code == null) {
          _stmt.bindNull(_argIndex)
        } else {
          _stmt.bindText(_argIndex, code)
        }
        _argIndex = 13
        if (code == null) {
          _stmt.bindNull(_argIndex)
        } else {
          _stmt.bindText(_argIndex, code)
        }
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
        while (_stmt.step()) {
          val _tmpKey: Long
          _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
          if (!_collectionPermissions.containsKey(_tmpKey)) {
            _collectionPermissions.put(_tmpKey, mutableListOf())
          }
        }
        _stmt.reset()
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
        val _result: MutableList<ClassEntityWithPermissions> = mutableListOf()
        while (_stmt.step()) {
          val _item: ClassEntityWithPermissions
          val _tmpClazz: ClassEntity
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
          val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
          val _tmpKey_1: Long
          _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
          _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
          _item = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
          _result.add(_item)
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun findByUidList(uids: List<Long>): List<ClassEntityWithPermissions> {
    val _stringBuilder: StringBuilder = StringBuilder()
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        SELECT ClassEntity.*")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("          FROM ClassEntity")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("         WHERE ClassEntity.cGuidHash in (")
    val _inputSize: Int = uids.size
    appendPlaceholders(_stringBuilder, _inputSize)
    _stringBuilder.append(") ")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("    ")
    val _sql: String = _stringBuilder.toString()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        for (_item: Long in uids) {
          _stmt.bindLong(_argIndex, _item)
          _argIndex++
        }
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
        while (_stmt.step()) {
          val _tmpKey: Long
          _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
          if (!_collectionPermissions.containsKey(_tmpKey)) {
            _collectionPermissions.put(_tmpKey, mutableListOf())
          }
        }
        _stmt.reset()
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
        val _result: MutableList<ClassEntityWithPermissions> = mutableListOf()
        while (_stmt.step()) {
          val _item_1: ClassEntityWithPermissions
          val _tmpClazz: ClassEntity
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
          val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
          val _tmpKey_1: Long
          _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
          _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
          _item_1 = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
          _result.add(_item_1)
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun findByInviteCode(code: String): List<ClassEntityWithPermissions> {
    val _sql: String = """
        |
        |        SELECT ClassEntity.*
        |          FROM ClassEntity
        |         WHERE ClassEntity.cStudentInviteGuid = ?
        |            OR ClassEntity.cTeacherInviteGuid = ? 
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindText(_argIndex, code)
        _argIndex = 2
        _stmt.bindText(_argIndex, code)
        val _columnIndexOfCGuid: Int = getColumnIndexOrThrow(_stmt, "cGuid")
        val _columnIndexOfCGuidHash: Int = getColumnIndexOrThrow(_stmt, "cGuidHash")
        val _columnIndexOfCTitle: Int = getColumnIndexOrThrow(_stmt, "cTitle")
        val _columnIndexOfCStatus: Int = getColumnIndexOrThrow(_stmt, "cStatus")
        val _columnIndexOfCDescription: Int = getColumnIndexOrThrow(_stmt, "cDescription")
        val _columnIndexOfCLastModified: Int = getColumnIndexOrThrow(_stmt, "cLastModified")
        val _columnIndexOfCStored: Int = getColumnIndexOrThrow(_stmt, "cStored")
        val _columnIndexOfCTeacherInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cTeacherInviteGuid")
        val _columnIndexOfCStudentInviteGuid: Int = getColumnIndexOrThrow(_stmt, "cStudentInviteGuid")
        val _collectionPermissions: LongSparseArray<MutableList<ClassPermissionEntity>> = LongSparseArray<MutableList<ClassPermissionEntity>>()
        while (_stmt.step()) {
          val _tmpKey: Long
          _tmpKey = _stmt.getLong(_columnIndexOfCGuidHash)
          if (!_collectionPermissions.containsKey(_tmpKey)) {
            _collectionPermissions.put(_tmpKey, mutableListOf())
          }
        }
        _stmt.reset()
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _collectionPermissions)
        val _result: MutableList<ClassEntityWithPermissions> = mutableListOf()
        while (_stmt.step()) {
          val _item: ClassEntityWithPermissions
          val _tmpClazz: ClassEntity
          val _tmpCGuid: String
          _tmpCGuid = _stmt.getText(_columnIndexOfCGuid)
          val _tmpCGuidHash: Long
          _tmpCGuidHash = _stmt.getLong(_columnIndexOfCGuidHash)
          val _tmpCTitle: String
          _tmpCTitle = _stmt.getText(_columnIndexOfCTitle)
          val _tmpCStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfCStatus).toInt()
          _tmpCStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpCDescription: String?
          if (_stmt.isNull(_columnIndexOfCDescription)) {
            _tmpCDescription = null
          } else {
            _tmpCDescription = _stmt.getText(_columnIndexOfCDescription)
          }
          val _tmpCLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfCLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfCLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCLastModified = _tmp_2
          }
          val _tmpCStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfCStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfCStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpCStored = _tmp_4
          }
          val _tmpCTeacherInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCTeacherInviteGuid)) {
            _tmpCTeacherInviteGuid = null
          } else {
            _tmpCTeacherInviteGuid = _stmt.getText(_columnIndexOfCTeacherInviteGuid)
          }
          val _tmpCStudentInviteGuid: String?
          if (_stmt.isNull(_columnIndexOfCStudentInviteGuid)) {
            _tmpCStudentInviteGuid = null
          } else {
            _tmpCStudentInviteGuid = _stmt.getText(_columnIndexOfCStudentInviteGuid)
          }
          _tmpClazz = ClassEntity(_tmpCGuid,_tmpCGuidHash,_tmpCTitle,_tmpCStatus,_tmpCDescription,_tmpCLastModified,_tmpCStored,_tmpCTeacherInviteGuid,_tmpCStudentInviteGuid)
          val _tmpPermissionsCollection: MutableList<ClassPermissionEntity>
          val _tmpKey_1: Long
          _tmpKey_1 = _stmt.getLong(_columnIndexOfCGuidHash)
          _tmpPermissionsCollection = checkNotNull(_collectionPermissions.get(_tmpKey_1))
          _item = ClassEntityWithPermissions(_tmpClazz,_tmpPermissionsCollection)
          _result.add(_item)
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun getLastModifiedAndHasPermission(
    authenticatedPersonUidNum: Long,
    classUidNum: Long,
    requiredPermission: Long,
  ): LastModifiedAndPermission {
    val _sql: String = """
        |
        |          WITH 
        |            AuthenticatedPermissionPersonUids(uidNum) AS (
        |                SELECT ? AS uidNum
        |                UNION
        |                SELECT PersonRelatedPersonEntity.prpOtherPersonUidNum AS uidNum
        |                  FROM PersonRelatedPersonEntity
        |                 WHERE 16 IN 
        |                       (SELECT PersonRoleEntity.prRoleEnum
        |                          FROM PersonRoleEntity
        |                         WHERE PersonRoleEntity.prPersonGuidHash = ?)
        |                   AND PersonRelatedPersonEntity.prpPersonUidNum = ?)     
        |        ,
        |               
        |        AuthenticatedUserEnrollments AS (
        |             SELECT EnrollmentEntity.*
        |               FROM EnrollmentEntity
        |              WHERE EnrollmentEntity.ePersonUidNum IN
        |                    (SELECT AuthenticatedPermissionPersonUids.uidNum
        |                       FROM AuthenticatedPermissionPersonUids)
        |                AND EnrollmentEntity.eStatus = 1
        |        )
        |        
        |        SELECT ? AS uidNum,
        |               (SELECT ClassEntity.cLastModified
        |                  FROM ClassEntity
        |                 WHERE ClassEntity.cGuidHash = ?) AS lastModified,
        |                 
        |               -- Begin permission check - slightly modified version of CLASS_PERMISSION_CHECK_SQL
        |               -- that uses classUidNum param instead of ClassEntity.cGuidHash. This way it also 
        |               -- works when checking permission to add a new class that does not yet exist
        |               (EXISTS(
        |                   SELECT 1
        |                     FROM SchoolPermissionGrantEntity
        |                    WHERE SchoolPermissionGrantEntity.spgToRole IN (
        |                          SELECT PersonRoleEntity.prRoleEnum
        |                            FROM PersonRoleEntity
        |                           WHERE PersonRoleEntity.prPersonGuidHash IN 
        |                                 (
        |            SELECT AuthenticatedPermissionPersonUids.uidNum
        |              FROM AuthenticatedPermissionPersonUids
        |        )) 
        |                      AND (SchoolPermissionGrantEntity.spgPermissions & ?) = ?
        |                      AND SchoolPermissionGrantEntity.spgStatusEnum = 1)
        |                OR EXISTS(
        |                   SELECT 1
        |                     FROM ClassPermissionEntity
        |                    WHERE ClassPermissionEntity.cpeClassUidNum = ?
        |                      AND ClassPermissionEntity.cpeToEnrollmentRole IN 
        |                          (SELECT AuthenticatedUserEnrollments.eRole
        |                             FROM AuthenticatedUserEnrollments
        |                            WHERE AuthenticatedUserEnrollments.eClassUidNum = ?)
        |                      AND (ClassPermissionEntity.cpePermissions & ?) = ?)
        |                ) AS hasPermission
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 2
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 3
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 4
        _stmt.bindLong(_argIndex, classUidNum)
        _argIndex = 5
        _stmt.bindLong(_argIndex, classUidNum)
        _argIndex = 6
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 7
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 8
        _stmt.bindLong(_argIndex, classUidNum)
        _argIndex = 9
        _stmt.bindLong(_argIndex, classUidNum)
        _argIndex = 10
        _stmt.bindLong(_argIndex, requiredPermission)
        _argIndex = 11
        _stmt.bindLong(_argIndex, requiredPermission)
        val _columnIndexOfUidNum: Int = getColumnIndexOrThrow(_stmt, "uidNum")
        val _columnIndexOfLastModified: Int = getColumnIndexOrThrow(_stmt, "lastModified")
        val _columnIndexOfHasPermission: Int = getColumnIndexOrThrow(_stmt, "hasPermission")
        val _result: LastModifiedAndPermission
        if (_stmt.step()) {
          val _tmpUidNum: Long
          _tmpUidNum = _stmt.getLong(_columnIndexOfUidNum)
          val _tmpLastModified: Long?
          if (_stmt.isNull(_columnIndexOfLastModified)) {
            _tmpLastModified = null
          } else {
            _tmpLastModified = _stmt.getLong(_columnIndexOfLastModified)
          }
          val _tmpHasPermission: Boolean
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfHasPermission).toInt()
          _tmpHasPermission = _tmp != 0
          _result = LastModifiedAndPermission(_tmpUidNum,_tmpLastModified,_tmpHasPermission)
        } else {
          error("The query result was empty, but expected a single row to return a NON-NULL object of type 'world.respect.datalayer.db.school.entities.LastModifiedAndPermission'.")
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  private fun __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection: SQLiteConnection, _map: LongSparseArray<MutableList<ClassPermissionEntity>>) {
    if (_map.isEmpty()) {
      return
    }
    if (_map.size() > 999) {
      recursiveFetchLongSparseArray(_map, true) { _tmpMap ->
        __fetchRelationshipClassPermissionEntityAsworldRespectDatalayerDbSchoolEntitiesClassPermissionEntity(_connection, _tmpMap)
      }
      return
    }
    val _stringBuilder: StringBuilder = StringBuilder()
    _stringBuilder.append("SELECT `cpeId`,`cpeClassUidNum`,`cpeToEnrollmentRole`,`cpePermissions` FROM `ClassPermissionEntity` WHERE `cpeClassUidNum` IN (")
    val _inputSize: Int = _map.size()
    appendPlaceholders(_stringBuilder, _inputSize)
    _stringBuilder.append(")")
    val _sql: String = _stringBuilder.toString()
    val _stmt: SQLiteStatement = _connection.prepare(_sql)
    var _argIndex: Int = 1
    for (i in 0 until _map.size()) {
      val _item: Long = _map.keyAt(i)
      _stmt.bindLong(_argIndex, _item)
      _argIndex++
    }
    try {
      val _itemKeyIndex: Int = getColumnIndex(_stmt, "cpeClassUidNum")
      if (_itemKeyIndex == -1) {
        return
      }
      val _columnIndexOfCpeId: Int = 0
      val _columnIndexOfCpeClassUidNum: Int = 1
      val _columnIndexOfCpeToEnrollmentRole: Int = 2
      val _columnIndexOfCpePermissions: Int = 3
      while (_stmt.step()) {
        val _tmpKey: Long
        _tmpKey = _stmt.getLong(_itemKeyIndex)
        val _tmpRelation: MutableList<ClassPermissionEntity>? = _map.get(_tmpKey)
        if (_tmpRelation != null) {
          val _item_1: ClassPermissionEntity
          val _tmpCpeId: Long
          _tmpCpeId = _stmt.getLong(_columnIndexOfCpeId)
          val _tmpCpeClassUidNum: Long
          _tmpCpeClassUidNum = _stmt.getLong(_columnIndexOfCpeClassUidNum)
          val _tmpCpeToEnrollmentRole: EnrollmentRoleEnum?
          val _tmp: Int?
          if (_stmt.isNull(_columnIndexOfCpeToEnrollmentRole)) {
            _tmp = null
          } else {
            _tmp = _stmt.getLong(_columnIndexOfCpeToEnrollmentRole).toInt()
          }
          if (_tmp == null) {
            _tmpCpeToEnrollmentRole = null
          } else {
            _tmpCpeToEnrollmentRole = __schoolTypeConverters.toEnrollmentRoleEnum(_tmp)
          }
          val _tmpCpePermissions: Long
          _tmpCpePermissions = _stmt.getLong(_columnIndexOfCpePermissions)
          _item_1 = ClassPermissionEntity(_tmpCpeId,_tmpCpeClassUidNum,_tmpCpeToEnrollmentRole,_tmpCpePermissions)
          _tmpRelation.add(_item_1)
        }
      }
    } finally {
      _stmt.close()
    }
  }

  public companion object {
    public fun getRequiredConverters(): List<KClass<*>> = emptyList()
  }
}
