Introduction: Why Swift and Databases?
\nSwift is not just a language for creating mobile applications. Thanks to frameworks like Vapor and SwiftNIO, developers can build full-fledged server applications that interact with relational and document-oriented databases. In this article, we will cover how to connect to PostgreSQL and MongoDB from Swift, and show simple code examples for beginners.
\nThe article is aimed at those who are already familiar with the basics of Swift but are just starting to learn how to work with databases. We will look at two popular approaches: classic SQL (PostgreSQL) and flexible NoSQL (MongoDB).
\n\n1. PostgreSQL in Swift: Structured Data
\nPostgreSQL is a powerful open-source relational database. To work with it in Swift, we will use the PostgresKit package, which is part of the Vapor ecosystem.
1.1 Installation and Setup
\nAdd the dependency to the Package.swift file:
// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n name: "MyApp",\n dependencies: [\n .package(url: "https://github.com/vapor/postgres-kit.git", from: "2.0.0")\n ],\n targets: [\n .executableTarget(\n name: "MyApp",\n dependencies: [\n .product(name: "PostgresKit", package: "postgres-kit")\n ]\n )\n ]\n)\n\n1.2 Connecting to the Database
\nCreate a configuration instance and connect to the PostgreSQL server:
\nimport PostgresKit\n\nlet eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)\ndefer { try! eventLoopGroup.syncShutdown() }\n\nlet configuration = PostgresConfiguration(\n hostname: "localhost",\n port: 5432,\n username: "swift_user",\n password: "secret",\n database: "swift_db"\n)\n\nlet pool = EventLoopGroupConnectionPool(\n source: PostgresConnectionSource(configuration: configuration),\n on: eventLoopGroup\n)\ndefer { try! pool.syncShutdown() }\n\nlet connection = try pool.requestConnection().wait()\nprint("Connection to PostgreSQL established!")\n\n1.3 Executing SQL Queries
\nNow let's execute a simple query to create a table and insert data:
\n// Create users table\ntry connection.query("""\n CREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n name TEXT NOT NULL,\n email TEXT UNIQUE NOT NULL\n )\n""").wait()\n\n// Insert data\ntry connection.query("""\n INSERT INTO users (name, email) \n VALUES ('Alexey', 'alex@example.com')\n""").wait()\n\n// Read data\nlet rows = try connection.query("SELECT * FROM users").wait()\nfor row in rows {\n let id = try row.decode(Int.self, column: "id")\n let name = try row.decode(String.self, column: "name")\n let email = try row.decode(String.self, column: "email")\n print("User: \\(name) (\\(email)), ID: \\(id)")\n}\n\n2. MongoDB in Swift: Flexible Documents
\nMongoDB is a NoSQL database that stores data in JSON-like documents. There are several drivers for Swift, but we will use the official MongoDB Swift Driver.
\n\n2.1 Installing the Driver
\nAdd the package to Package.swift:
dependencies: [\n .package(url: "https://github.com/mongodb/mongo-swift-driver.git", from: "1.0.0")\n],\ntargets: [\n .executableTarget(\n name: "MyApp",\n dependencies: [\n .product(name: "MongoSwift", package: "mongo-swift-driver")\n ]\n )\n]\n\n2.2 Connecting to MongoDB
\nCreate a client and select a database:
\nimport MongoSwift\n\nlet client = try MongoClient("mongodb://localhost:27017")\ndefer { try? client.syncClose() }\n\nlet database = client.db("swift_m