Skip to content

Commit 0af33d8

Browse files
committed
Add check for temporary or purely in-memory path when incrementing newConnection
1 parent f9dc90e commit 0af33d8

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

sqliter-driver/src/nativeCommonMain/kotlin/co/touchlab/sqliter/native/NativeDatabaseManager.kt

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,18 @@ class NativeDatabaseManager(private val path:String,
9797
conn.close()
9898
throw e
9999
}
100-
newConnection.increment()
100+
101+
// Temporary, or purely in-memory databases live only as long
102+
// as the connection. Subsequent connections (even if open at
103+
// the same time) are completely separate databases.
104+
//
105+
// If this is the case, do not increment newConnection so that
106+
// this if block executes on every new connection (i.e. ever new
107+
// ephemeral database).
108+
when (path) {
109+
"", ":memory:" -> {}
110+
else -> newConnection.increment()
111+
}
101112
}
102113

103114
conn

sqliter-driver/src/nativeCommonTest/kotlin/co/touchlab/sqliter/DatabaseManagerTest.kt

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,66 @@ class DatabaseManagerTest : BaseDatabaseTest(){
8686
assertEquals(1, updateCalled.value)
8787
}
8888

89+
@Test
90+
fun createCalledEachNewConnectionWhenInMemory() {
91+
var creationCount = 0
92+
93+
val conf = DatabaseConfiguration(
94+
name = null,
95+
inMemory = true,
96+
version = 1, create = { db ->
97+
creationCount++
98+
db.withStatement(TWO_COL) {
99+
execute()
100+
}
101+
},
102+
)
103+
104+
val mgr = createDatabaseManager(conf)
105+
mgr.withConnection {
106+
it.rawExecSql("INSERT INTO test(num, str)values(3,'abc')")
107+
assertEquals(1, it.longForQuery("select count(*) from test"))
108+
109+
mgr.withConnection {
110+
assertEquals(0, it.longForQuery("select count(*) from test"))
111+
}
112+
}
113+
114+
assertEquals(2, creationCount)
115+
}
116+
117+
@Test
118+
fun createCalledEachNewConnectionWhenTemporary() {
119+
var creationCount = 0
120+
121+
val conf = DatabaseConfiguration(
122+
name = "",
123+
inMemory = true,
124+
version = 1,
125+
create = { db ->
126+
creationCount++
127+
db.withStatement(TWO_COL) {
128+
execute()
129+
}
130+
},
131+
extendedConfig = DatabaseConfiguration.Extended(
132+
basePath = ""
133+
),
134+
)
135+
136+
val mgr = createDatabaseManager(conf)
137+
mgr.withConnection { conn1 ->
138+
conn1.rawExecSql("INSERT INTO test(num, str)values(3,'abc')")
139+
assertEquals(1, conn1.longForQuery("select count(*) from test"))
140+
141+
mgr.withConnection { conn2 ->
142+
assertEquals(0, conn2.longForQuery("select count(*) from test"))
143+
}
144+
}
145+
146+
assertEquals(2, creationCount)
147+
}
148+
89149
@Test
90150
fun downgradeNotAllowed(){
91151
val upgradeCalled = AtomicInt(0)

0 commit comments

Comments
 (0)