anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: cashapp/sqldelight
Issue: java.lang.NullPointerException in SqlDelightFoldingBuilder.kt:79

## Error in SQL Delight IntelliJ Plugin

**java.lang.NullPointerException** in **SqlDelightFoldingBuilder.kt:79**
nextSibling must not be null

[View on Bugsnag](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60967a6f7d8e8d000751a733?event_id=60967a6f007a892c354a0000&i=gh&m=ci)

## Stacktrace

    SqlDelightFoldingBuilder.kt:79 - com.squareup.sqldelight.intellij.lang.SqlDelightFoldingBuilder.toCreateTableDescriptor
    SqlDelightFoldingBuilder.kt:56 - com.squareup.sqldelight.intellij.lang.SqlDelightFoldingBuilder.createFoldingDescriptors
    SqlDelightFoldingBuilder.kt:39 - com.squareup.sqldelight.intellij.lang.SqlDelightFoldingBuilder.buildFoldRegions

[View full stacktrace](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60967a6f7d8e8d000751a733?event_id=60967a6f007a892c354a0000&i=gh&m=ci)

*Created automatically via Bugsnag*

Changed files:
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt

diff --git a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt
index cb35f7e56..f4057b916 100644
--- a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt
+++ b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt
@@ -76,7 +76,7 @@ class SqlDelightFoldingBuilder : FoldingBuilder, DumbAware {
   private fun PsiElement.toCreateTableDescriptor(createTableStmt: PsiElement?): FoldingDescriptor? {
     val openingBraceElement = createTableStmt?.node?.findChildByType(SqlTypes.LP) ?: return null
     val start = openingBraceElement.startOffset
-    val end = nextSibling.endOffset
+    val end = nextSibling?.endOffset ?: 0
     if (start >= end) return null
     return FoldingDescriptor(this, start, end, null, "(...);")
   }
Repository: cashapp/sqldelight
Issue: Memory leak in native code when using sqlite-driver 1.5.0

**Runtime Environment**
SQLDelight version: 1.5.0
Application OS: JVM: MacOS/Linux

Given this schema:

```sql
CREATE TABLE TestTable (
    uuid TEXT NOT NULL PRIMARY KEY,
    some_text TEXT NOT NULL,
    some_timestamp INTEGER NOT NULL
);
```

executing the following query every 100ms: 

```sql
getLatest:
SELECT uuid, some_text, some_timestamp
FROM TestTable
ORDER BY some_timestamp DESC
LIMIT 1;
```

using this code:

```kotlin
fun main() {
  val driver = JdbcSqliteDriver("jdbc:sqlite:leakdb.sqlite")
  val db = TestDb(driver)

  // Code used to populate the db:
  //  TestDb.Schema.create(driver)
  //  repeat(500) {
  //    db.testTableQueries.insertOne(UUID.randomUUID().toString(), "Hello", (Math.random() * 1000000L).toLong())
  //  }

  runBlocking {
    launch {
      while (isActive) {
        db.testTableQueries.getLatest().executeAsOneOrNull()
        delay(100)
      }
    }
  }
}
```

results in continuous memory allocations that do not get freed again. 

When printing out the memory usage of the process every two seconds, the output is as follows:

```
Memory usage: 52,00M
Memory usage: 64,90M
Memory usage: 68,40M
Memory usage: 71,93M
Memory usage: 75,45M
Memory usage: 79,13M
Memory usage: 85,96M
Memory usage: 89,61M
```

Whereas changing the version of `sqlite-driver` to 1.4.4 results in this:

```
Memory usage: 61,52M
Memory usage: 63,04M
Memory usage: 63,07M
Memory usage: 63,11M
Memory usage: 63,14M
Memory usage: 63,16M
```

I tried to look into this using JConsole, and the allocations seem to happen off the heap, I suspect somewhere in SQLite/Xerial native code. Forced GCs thus don't have any effect. ~I also tried forcing Xerial version `3.21.0.1` (with both `sqlite-driver` `1.4.4` and `1.5.0`), but it didn't have any effect either.~ Using an in-memory DB results in a lot less memory being allocated.

Proof of concept/sample project: https://github.com/hannesstruss/sqldelight_memory

Changed files:
drivers/sqlite-driver/src/main/kotlin/com/squareup/sqldelight/sqlite/driver/JdbcSqliteDriver.kt

diff --git a/drivers/sqlite-driver/src/main/kotlin/com/squareup/sqldelight/sqlite/driver/JdbcSqliteDriver.kt b/drivers/sqlite-driver/src/main/kotlin/com/squareup/sqldelight/sqlite/driver/JdbcSqliteDriver.kt
index 0d6c509ee..8a2d34168 100644
--- a/drivers/sqlite-driver/src/main/kotlin/com/squareup/sqldelight/sqlite/driver/JdbcSqliteDriver.kt
+++ b/drivers/sqlite-driver/src/main/kotlin/com/squareup/sqldelight/sqlite/driver/JdbcSqliteDriver.kt
@@ -67,7 +67,10 @@ private class ThreadedConnectionManager(
 
   override fun closeConnection(connection: Connection) {
     check(connections.get() == connection) { "Connections must be closed on the thread that opened them" }
-    if (transaction == null) connections.remove()
+    if (transaction == null) {
+      connection.close()
+      connections.remove()
+    }
   }
 
   override fun close() = Unit
Repository: cashapp/sqldelight
Issue: java.lang.NullPointerException in SqlDelightGotoDeclarationHandler.kt:134

## Error in SQL Delight IntelliJ Plugin

**java.lang.NullPointerException** in **SqlDelightGotoDeclarationHandler.kt:134**
resolved.containingFile.virtualFile must not be null

[View on Bugsnag](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60f4e1c961242100076bb15c?event_id=60f4e1c9007f924898230000&i=gh&m=ci)

## Stacktrace

    SqlDelightGotoDeclarationHandler.kt:134 - com.squareup.sqldelight.intellij.SqlDelightGotoDeclarationHandler.targetData
    SqlDelightGotoDeclarationHandler.kt:61 - com.squareup.sqldelight.intellij.SqlDelightGotoDeclarationHandler.getGotoDeclarationTargets

[View full stacktrace](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60f4e1c961242100076bb15c?event_id=60f4e1c9007f924898230000&i=gh&m=ci)

*Created automatically via Bugsnag*

Changed files:
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt

diff --git a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
index 2d7410868..46566e64f 100644
--- a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
+++ b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
@@ -62,7 +62,7 @@ class SqlDelightGotoDeclarationHandler : GotoDeclarationHandler {
     val function = targetData.function
     val elementFile = targetData.containingFile
 
-    val module = elementFile.getModule(function.project) ?: return emptyArray()
+    val module = elementFile?.getModule(function.project) ?: return emptyArray()
 
     // Only handle files under the generated sqlite directory.
     val fileIndex = SqlDelightFileIndex.getInstance(module)
@@ -131,7 +131,7 @@ class SqlDelightGotoDeclarationHandler : GotoDeclarationHandler {
       is KtNamedFunction, is PsiMethod -> TargetData(
         parameter = null,
         function = resolved as PsiNamedElement,
-        containingFile = resolved.containingFile.virtualFile
+        containingFile = resolved.containingFile?.virtualFile
       )
       else -> null
     }
@@ -142,6 +142,6 @@ class SqlDelightGotoDeclarationHandler : GotoDeclarationHandler {
   data class TargetData(
     val parameter: PsiNamedElement?,
     val function: PsiNamedElement,
-    val containingFile: VirtualFile
+    val containingFile: VirtualFile?
   )
 }
Repository: cashapp/sqldelight
Issue: Paste text inside TABLE section also adds two empty lines at file start

**Build Environment**
SQLDelight version: 1.5.0
IDE version: Android Studio Arctic Fox | 2020.3.1 Beta 3
Dialect: both MySQL and SQLite

1. Create new table
2. insert any text inside table block, like a new row
3. two new lines gets added to the file start

I tried turning off all external plugins except SQLDelight.

After AS restart while the plugin is starting new lines are not appearing

https://user-images.githubusercontent.com/6103621/121422447-711f7b80-c999-11eb-83c4-1b113d07fd05.mov






Changed files:
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightCopyPasteProcessor.kt

diff --git a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightCopyPasteProcessor.kt b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightCopyPasteProcessor.kt
index b89d328fe..0f7a6bc56 100644
--- a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightCopyPasteProcessor.kt
+++ b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightCopyPasteProcessor.kt
@@ -99,6 +99,11 @@ class SqlDelightCopyPasteProcessor : CopyPastePostProcessor<ReferenceTransferabl
       return
     }
 
+    val references = values.first().data
+    if (references.isNullOrEmpty()) {
+      return
+    }
+
     val document = editor.document
     val documentManager = PsiDocumentManager.getInstance(project)
     val file = documentManager.getPsiFile(document)
@@ -115,7 +120,7 @@ class SqlDelightCopyPasteProcessor : CopyPastePostProcessor<ReferenceTransferabl
     documentManager.commitAllDocuments()
 
     WriteCommandAction.writeCommandAction(project).run<ReadOnlyModificationException> {
-      val qClassNames = values.first().data.map(ReferenceData::qClassName)
+      val qClassNames = references.map(ReferenceData::qClassName)
       val importStmtList = file.findChildOfType<SqlDelightImportStmtList>()?.importStmtList.orEmpty()
       val oldImports = importStmtList.map { it.javaType.text }
       val newImports = (qClassNames + oldImports).distinct()
Repository: cashapp/sqldelight
Issue: org.jetbrains.kotlin.idea.caches.resolve.KotlinIdeaResolutionException in SqlDelightGotoDeclarationHandler.kt:45

## Error in SQL Delight IntelliJ Plugin

**org.jetbrains.kotlin.idea.caches.resolve.KotlinIdeaResolutionException** in **SqlDelightGotoDeclarationHandler.kt:45**
Kotlin resolution encountered a problem while analyzing KtNameReferenceExpression

[View on Bugsnag](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60757aefb2329e0007581bb6?event_id=60757aef00775b232dea0000&i=gh&m=ci)

## Stacktrace

    SqlDelightGotoDeclarationHandler.kt:45 - com.squareup.sqldelight.intellij.SqlDelightGotoDeclarationHandler.getGotoDeclarationTargets

[View full stacktrace](https://app.bugsnag.com/square-inc/sql-delight-intellij-plugin/errors/60757aefb2329e0007581bb6?event_id=60757aef00775b232dea0000&i=gh&m=ci)

*Created automatically via Bugsnag*

Changed files:
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt

diff --git a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
index fa8e9fa08..6de36e2dc 100644
--- a/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
+++ b/sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightGotoDeclarationHandler.kt
@@ -32,6 +32,7 @@ import com.squareup.sqldelight.intellij.util.isAncestorOf
 import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
 import org.jetbrains.kotlin.idea.util.projectStructure.getModule
 import org.jetbrains.kotlin.psi.KtNameReferenceExpression
+import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
 import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
 
 class SqlDelightGotoDeclarationHandler : GotoDeclarationHandler {
@@ -42,11 +43,16 @@ class SqlDelightGotoDeclarationHandler : GotoDeclarationHandler {
   ): Array<PsiElement> {
     if (sourceElement == null) return emptyArray()
 
-    val elementFile = when (sourceElement.parent) {
-      is PsiReference -> sourceElement.parent as PsiReference
-      is KtNameReferenceExpression -> sourceElement.parent.references.firstIsInstance<KtSimpleNameReference>()
-      else -> return emptyArray()
-    }.resolve()?.containingFile?.virtualFile ?: return emptyArray()
+    val elementFile = try {
+      when (sourceElement.parent) {
+        is PsiReference -> sourceElement.parent as PsiReference
+        is KtNameReferenceExpression -> sourceElement.parent.references.firstIsInstance<KtSimpleNameReference>()
+        else -> return emptyArray()
+      }.resolve()?.containingFile?.virtualFile ?: return emptyArray()
+    } catch (e: KotlinExceptionWithAttachments) {
+      // Resolution failed, just ignore.
+      return emptyArray()
+    }
 
     val module = elementFile.getModule(sourceElement.project) ?: return emptyArray()