2

I need to get full sql query of query interface in order to save them in user defaults but i couldn't find this functionality

update: in order to achieve full query string:

  1. including arguments that were trimmed by sqlite for injection you can not replace those arguments with question mark manualy.

  2. you can not achieve real value of those arguments because they are private

Hamed Nova
  • 1,061
  • 9
  • 15

3 Answers3

2

There is a trace function in the latest GRDB:

// Prints all SQL statements
var config = Configuration()
config.prepareDatabase { db in
    db.trace { print($0) }
}
Aliaksandr Bialiauski
  • 1,541
  • 20
  • 25
1

The How do I print a request as SQL? FAQ says:

You can turn your request into a SQLRequest instance:

try dbQueue.read { db in
    let request = Wine
        .filter(Column("origin") == "Burgundy")
        .order(Column("price")

    let sqlRequest = try SQLRequest(db, request: request)
    print(sqlRequest.sql)
    // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
    print(sqlRequest.arguments)
    // Prints ["Burgundy"]
}
Gwendal Roué
  • 3,949
  • 15
  • 34
  • first of all thanks for your answer. i know this but in order to achieve full query string including arguments that were trimmed by sqlite for injection you can not replace those arguments with question mark manualy.another cons is you can not achieve real value of those arguments because they are private – Hamed Nova Apr 24 '19 at 10:34
  • 1
    OK @nova. Next time you ask a question on SO, will you please make sure you tell what you already know, so that both the question and answers are better focused? This will help everybody, not only you. Now your comment is about something else. I suggest you ask another question, or, if some feature is missing, open a Github issue. – Gwendal Roué Apr 24 '19 at 10:48
  • Good Point. i will update the question, i didn't know it from the time when i asked the question. – Hamed Nova Apr 27 '19 at 11:18
0

For newer versions of GRDB, the answer is different.

taken from How do I print a request as SQL? :

try dbQueue.read { db in
    let request = Player.filter(Column("email") == "arthur@example.com")
    let statement = try request.makePreparedRequest(db).statement
    print(statement) // SELECT * FROM player WHERE email = ?
    print(statement.arguments) // ["arthur@example.com"]
}
Lutzifer
  • 755
  • 1
  • 6
  • 11