Sqlite.swift: Question: How could I check if column already exists, before adding it?

Created on 10 Jul 2017  路  2Comments  路  Source: stephencelis/SQLite.swift

Hi, thanks for developing SQLite.swift!

I want to add columns from code, and would like to check if column already exists. How can I do it?

Thanks!!!

Most helpful comment

This is how I solved it:
````
extension Connection {
public func exists(column: String, in table: String) throws -> Bool {
let stmt = try prepare("PRAGMA table_info((table))")

    let columnNames = stmt.makeIterator().map { (row) -> String in
        return row[1] as? String ?? ""
    }

    return columnNames.contains(where: { dbColumn -> Bool in
        return dbColumn.caseInsensitiveCompare(column) == ComparisonResult.orderedSame
    })
}

}
````

All 2 comments

This is how I solved it:
````
extension Connection {
public func exists(column: String, in table: String) throws -> Bool {
let stmt = try prepare("PRAGMA table_info((table))")

    let columnNames = stmt.makeIterator().map { (row) -> String in
        return row[1] as? String ?? ""
    }

    return columnNames.contains(where: { dbColumn -> Bool in
        return dbColumn.caseInsensitiveCompare(column) == ComparisonResult.orderedSame
    })
}

}
````

This is how I solved it:

extension Connection {
    public func exists(column: String, in table: String) throws -> Bool {
        let stmt = try prepare("PRAGMA table_info(\(table))")

        let columnNames = stmt.makeIterator().map { (row) -> String in
            return row[1] as? String ?? ""
        }

        return columnNames.contains(where: { dbColumn -> Bool in
            return dbColumn.caseInsensitiveCompare(column) == ComparisonResult.orderedSame
        })
    }
}

thx) and how check record is already exist? (i want know i must update or insert)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tommycloud picture tommycloud  路  6Comments

Tchoupinax picture Tchoupinax  路  8Comments

Viswanth92 picture Viswanth92  路  3Comments

pgawlowski picture pgawlowski  路  6Comments

leminhtuan2015 picture leminhtuan2015  路  5Comments