Joseph Jude

Technology, Psychology, and Story Telling

Export sqlite data to text files using Swift

Posted: Tags: code,swift

I had my blog post details in a sqlite. I wanted them converted into text files, so that I can store them in a git repository.

Though I could've written the script in python, I wanted to try swift. Surprisingly, it was easy to do in swift. I used two toolkits—SQLite and FileKit, which made this easy.

I used Carthage as a package manager. If you want a good tutorial on Carthage, checkout the tutorial at Ray Wenderlich.

Once you install carthage, create a cartfile for the frameworks:

github "stephencelis/SQLite.swift" ~> 0.10.1
github "nvzqz/FileKit"

Now, you have to download these frameworks and build them locally. carthage update --no-use-binaries will just do that.

Here is the code to connect to sqlite and export the content of a table into a structure text file:

#!/usr/bin/swift -F Carthage/Build/Mac/

// Tell Swift where to find sqlite & filekit framework.

import SQLite
import FileKit

let db = try Connection("posts.db")

let fileDirectory = Path.Current + "out"
var fileName = ""

for row in try db.prepare("SELECT * FROM entry") {
    // construct fileName; convert path & row value to string
    fileName = String(fileDirectory) + "/" + String(row[6]!) + ".md"

    // convert string to Path
    let postFile = TextFile(path: Path(fileName))

    try "Site: " + String(row[1]!) |> postFile 
    try "Title: " + String(row[9]!) |>> postFile
    try "Subtitle: " + String(row[7]!) |>> postFile
    try "Date: " + String(row[5]!) |>> postFile
    try "Slug: " + String(row[6]!) |>> postFile
    try "Tags: " + String(row[8]!) |>> postFile
    try "Type: " + String(row[4]!) |>> postFile
    try "Excerpt: " + String(row[3]!) |>> postFile
    try "


Like the post? Retweet it. Got comments? Reply.

Comments

comments powered by Disqus