SQLite User Forum

Failing to ATTACH to an external database using URI
Login

Failing to ATTACH to an external database using URI

(1) By PazO (JohnSmith) on 2022-07-19 12:01:38 [source]

I am trying to attach to an external database using the ATTACH command.
Until now I was doing this using the conventional path string (D:\Path\File.ext) and all was working fine. Currently due to other requirement (attach to READ-ONLY files) I am trying to use the URI naming convention, but the ATTACH command keeps on failing with error 14: 'unable to open database'.

Reason for using URI:
In my code, sometimes I load data into the open-connection, from an external database using the following flow:

  1. ATTACH 'file.ext' AS 'SRC_DB'
  2. BEGIN IMMEDIATE TRANSACTION
  3. INSERT INTO t1 SELECT * FROM SRC_DB.t1
  4. INSERT INTO t2 SELECT * FROM SRC_DB.t2
  5. ...
  6. END TRANSACTION
  7. DETACH 'SRC_DB'

The above flow works fine for source-db, which have READ/WRITE permissions. The problem is that with file with READ-ONLY permission the BEGIN IMMEDIATE TRANSACTION will fail on READ-ONLY error (even though I did not try to write to it).

I thought that using URI may solve this (?) by specifying that source-DB should be opened in READ-ONLY mode.
Something in the form of:
ATTACH 'file:///D:/Path/ReadOnly.db?mode=ro' 'SRC_DB'

The problem is that I cannot get the ATTACH to work with URI at all. I also tried this with db that have READ/WRITE permissions, but nothing works.

I tried:

  • 'file:///D:/Path/ReadOnly.db?mode=ro'
  • 'file:///D:/Path/ReadOnly.db'
  • 'file:///D:\Path\ReadOnly.db'

But to no avail.

Could someone give me a hint what am I doing wrong?

Thanks!

(2) By anonymous on 2022-07-19 13:00:13 in reply to 1 [link] [source]

Instead of

ATTACH 'file:///D:/Path/ReadOnly.db?mode=ro' 'SRC_DB'

try

ATTACH 'file:///D:/Path/ReadOnly.db?mode=ro' AS SRC_DB;

(3) By Stephan Beal (stephan) on 2022-07-19 13:05:38 in reply to 1 [link] [source]

Could someone give me a hint what am I doing wrong?

Make sure that URI support is enabled in your build (it is off by default):

https://sqlite.org/uri.html (section 2)

(4) By PazO (JohnSmith) on 2022-07-19 16:42:37 in reply to 3 [link] [source]

Thank you Stephan!

This fixed it for me.