From eb89b7669d66fd7c4cdf8434a1db1bb92fca1a3a Mon Sep 17 00:00:00 2001
From: Howon Lee <hlee.howon@gmail.com>
Date: Tue, 8 Jun 2021 10:38:00 -0700
Subject: [PATCH] Detect if file is blank or bad for SQLite DB connection
 (#16372)

Previously just used JDBC. However, JDBC will merrily execute queries on empty file locations for SQLite, because it'll create a new SQLite file. This one checks that there exists a SQLite file already to be querying in the first place
---
 .../sqlite/src/metabase/driver/sqlite.clj     | 20 ++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/modules/drivers/sqlite/src/metabase/driver/sqlite.clj b/modules/drivers/sqlite/src/metabase/driver/sqlite.clj
index ec76491fb70..88d23de96ed 100644
--- a/modules/drivers/sqlite/src/metabase/driver/sqlite.clj
+++ b/modules/drivers/sqlite/src/metabase/driver/sqlite.clj
@@ -1,5 +1,6 @@
 (ns metabase.driver.sqlite
-  (:require [clojure.string :as str]
+  (:require [clojure.java.io :as io]
+            [clojure.string :as str]
             [honeysql.core :as hsql]
             [honeysql.format :as hformat]
             [java-time :as t]
@@ -38,6 +39,23 @@
 ;; for now we'll just skip the foreign key stuff in the tests.
 (defmethod driver/supports? [:sqlite :foreign-keys] [_ _] (not config/is-test?))
 
+;; Every SQLite3 file starts with "SQLite Format 3"
+;; or "** This file contains an SQLite
+;; There is also SQLite2 but last 2 version was 2005
+(defn- confirm-file-is-sqlite [filename]
+  (with-open [reader (io/input-stream filename)]
+    (let [outarr (byte-array 50)]
+      (.read reader outarr)
+      (let [line (String. outarr)]
+        (or (str/includes? line "SQLite format 3")
+            (str/includes? line "This file contains an SQLite"))))))
+
+(defmethod driver/can-connect? :sqlite
+  [driver details]
+  (if (confirm-file-is-sqlite (:db details))
+    (sql-jdbc.conn/can-connect? driver details)
+    false ))
+
 (defmethod driver/db-start-of-week :sqlite
   [_]
   :sunday)
-- 
GitLab