{"id":28467852,"url":"https://github.com/kitura/swift-kuery-postgresql","last_synced_at":"2025-07-14T03:08:36.434Z","repository":{"id":41394944,"uuid":"68811836","full_name":"Kitura/Swift-Kuery-PostgreSQL","owner":"Kitura","description":"PostgreSQL plugin for Swift-Kuery framework","archived":false,"fork":false,"pushed_at":"2021-12-17T18:15:19.000Z","size":904,"stargazers_count":62,"open_issues_count":9,"forks_count":34,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-07-01T09:44:34.375Z","etag":null,"topics":["linux","macos","postgresql","relational-databases","swift","swift-kuery-framework"],"latest_commit_sha":null,"homepage":"https://kitura.github.io/Swift-Kuery-PostgreSQL/","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Kitura.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-09-21T11:51:18.000Z","updated_at":"2024-11-22T14:48:04.000Z","dependencies_parsed_at":"2022-09-24T14:51:53.493Z","dependency_job_id":null,"html_url":"https://github.com/Kitura/Swift-Kuery-PostgreSQL","commit_stats":null,"previous_names":[],"tags_count":45,"template":false,"template_full_name":null,"purl":"pkg:github/Kitura/Swift-Kuery-PostgreSQL","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FSwift-Kuery-PostgreSQL","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FSwift-Kuery-PostgreSQL/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FSwift-Kuery-PostgreSQL/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FSwift-Kuery-PostgreSQL/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Kitura","download_url":"https://codeload.github.com/Kitura/Swift-Kuery-PostgreSQL/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FSwift-Kuery-PostgreSQL/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265236926,"owners_count":23732504,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["linux","macos","postgresql","relational-databases","swift","swift-kuery-framework"],"created_at":"2025-06-07T08:05:39.935Z","updated_at":"2025-07-14T03:08:36.426Z","avatar_url":"https://github.com/Kitura.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"http://kitura.io/\"\u003e\n        \u003cimg src=\"https://raw.githubusercontent.com/Kitura/Kitura/master/Sources/Kitura/resources/kitura-bird.svg?sanitize=true\" height=\"100\" alt=\"Kitura\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://kitura.github.io/Swift-Kuery-PostgreSQL/index.html\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/apidoc-SwiftKueryPostgreSQL-1FBCE4.svg?style=flat\" alt=\"APIDoc\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://travis-ci.org/Kitura/Swift-Kuery-PostgreSQL\"\u003e\n    \u003cimg src=\"https://travis-ci.org/Kitura/Swift-Kuery-PostgreSQL.svg?branch=master\" alt=\"Build Status - Master\"\u003e\n    \u003c/a\u003e\n    \u003cimg src=\"https://img.shields.io/badge/os-macOS-green.svg?style=flat\" alt=\"macOS\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/os-linux-green.svg?style=flat\" alt=\"Linux\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/license-Apache2-blue.svg?style=flat\" alt=\"Apache 2\"\u003e\n    \u003ca href=\"http://swift-at-ibm-slack.mybluemix.net/\"\u003e\n    \u003cimg src=\"http://swift-at-ibm-slack.mybluemix.net/badge.svg\" alt=\"Slack Status\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n# Swift-Kuery-PostgreSQL\n\n[PostgreSQL](https://www.postgresql.org/) plugin for the [Swift-Kuery](https://github.com/Kitura/Swift-Kuery) framework. It enables you to use Swift-Kuery to manipulate data in a PostgreSQL database.\n\n## PostgreSQL client installation\nTo use Swift-Kuery-PostgreSQL you must have the appropriate PostgreSQL C-language client installed.\n\n### macOS\n```\n$ brew install postgresql\n```\n\n### Linux\n```\n$ sudo apt-get install libpq-dev\n```\n\n## Usage\n\n#### Add dependencies\n\nAdd the `SwiftKueryPostgreSQL` package to the dependencies within your application’s `Package.swift` file. Substitute `\"x.x.x\"` with the latest `SwiftKueryPostgreSQL` [release](https://github.com/Kitura/Swift-Kuery-PostgreSQL/releases).\n\n```swift\n.package(url: \"https://github.com/Kitura/Swift-Kuery-PostgreSQL.git\", from: \"x.x.x\")\n```\n\nAdd `SwiftKueryPostgreSQL` to application's dependencies:\n\n```swift\n.target(name: \"Application\", dependencies: [\"SwiftKueryPostgreSQL\"]),\n```\n\n#### Import package\n\n  ```swift\n  import SwiftKueryPostgreSQL\n  ```\n\n## Using Swift-Kuery-PostgreSQL\n\nFirst create an instance of `Swift-Kuery-PostgreSQL` by calling:\n\n```swift\nlet connection = PostgreSQLConnection(host: host, port: port, options: [ConnectionOptions]?)\n```\n**Where:**\n- *host* and *port* are the host and the port of PostgreSQL\n- *ConnectionOptions*  an optional set of:\n   * *options* - command-line options to be sent to the server\n   * *databaseName* - the database name\n   * *userName* - the user name\n   * *password* - the user password\n   * *connectionTimeout* - maximum wait for connection in seconds. Zero or not specified means wait indefinitely.\n\nFor more details refer to the [PostgreSQL manual](https://www.postgresql.org/docs/8.0/static/libpq.html#LIBPQ-CONNECT).\n\n\u003cbr\u003e\n\nAlternatively, call:\n\n```swift\nlet connection = PostgreSQLConnection(url: URL(string: \"Postgres://\\(username):\\(password)@\\(host):\\(port)/\\(databaseName)\")!)\n```\n\nTo establish a connection to the database call:\n\n```swift\nconnection.connect() { result in\n    guard result.success else {\n        // Connection not established, handle error\n        return\n    }\n    // Connection established\n}\n```\nYou now have a connection that can be used to execute SQL queries created using Swift-Kuery.\n\n## Getting Started with Swift-Kuery-PostgreSQL locally\n\n### Install PostgreSQL server\n\n#### Mac\n```\nbrew install postgresql\n```\n\n#### Ubuntu Linux\n```\nsudo apt-get install postgresql postgresql-contrib\n```\n\nMake sure you have the database running. This installation should have also installed two applications we need, namely (createdb and psql) which will be used as clients to your locally running PostgreSQL.\n### Create a database\nLet's create a database called `school`:\n```\ncreatedb school\n```\n\n### Create the tables\nNow, let's create the tables we need for this example.\n\nUse the interative `psql` client to open the database we created:\n\n```\n$ psql school\npsql (9.5.4)\nType \"help\" for help.\n\nschool=#\n```\n\nFirst, create the student table:\n\n```sql\nCREATE TABLE student (\n studentId BIGSERIAL PRIMARY KEY,\n name varchar(100) NOT NULL CHECK (name \u003c\u003e '')\n);\n```\n\nNext, create the grades table:\n\n```sql\nCREATE TABLE grades (\n  key BIGSERIAL PRIMARY KEY,\n  studentId integer NOT NULL,\n  course varchar(40) NOT NULL,\n  grade integer\n);\n```\n\n### Populate the tables\n\nFirst the students table:\n\n```sql\nINSERT INTO student VALUES (1, 'Tommy Watson');\nINSERT INTO student VALUES (2, 'Fred Flintstone');\n```\n\nAnd then the grades table:\n\n```sql\nINSERT INTO grades (studentId, course, grade) VALUES (1, 'How to build your first computer', 99);\nINSERT INTO grades (studentId, course, grade) VALUES (2, 'How to work at a rock quarry', 71);\n```\n\n### Use Swift-Kuery\nNow we are set to connect to our database from Swift and use Swift-Kuery to query the data into our Swift application.\n\n#### Create simple Swift executable\nFirst create a directory for our project and then initialize it.\n\n```\n$ mkdir swift-kuery-play\n$ cd swift-kuery-play\n$ swift package init --type executable\nCreating executable package: swift-kuery-play\nCreating Package.swift\nCreating README.md\nCreating .gitignore\nCreating Sources/\nCreating Sources/swift-kuery-play/main.swift\nCreating Tests/\n$\n```\n\nNow, add Swift-Kuery-PostgreSQL as a dependency for our project, this will automatically pull in Swift-Kuery.\nEdit `Package.swift` to contain the following, substituting `\"x.x.x\"` with the latest `Kitura` and `Swift-Kuery-PostgreSQL` releases.\n\n```swift\n// swift-tools-version:4.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"swift-kuery-play\",\n    dependencies: [\n        .package(url: \"https://github.com/Kitura/Kitura.git\", from: \"x.x.x\"),\n        .package(url: \"https://github.com/Kitura/Swift-Kuery-PostgreSQL\", from: \"x.x.x\")\n    ],\n    targets: [\n        .target(\n            name: \"swift-kuery-play\",\n            dependencies: [\"Kitura\", \"SwiftKueryPostgreSQL\"]),\n    ]\n)\n```\n\nNow, edit your `main.swift` file to contain:\n\n```swift\nimport SwiftKuery\nimport SwiftKueryPostgreSQL\nimport Kitura\n\nlet router = Router()\n\nclass Grades : Table {\n  let tableName = \"grades\"\n  let key = Column(\"key\")\n  let course = Column(\"course\")\n  let grade = Column(\"grade\")\n  let studentId = Column(\"studentId\")\n}\n\nlet grades = Grades()\n\nlet connection = PostgreSQLConnection(host: \"localhost\", port: 5432, options: [.databaseName(\"school\")])\n\nfunc grades(_ callback: @escaping (String) -\u003e Void) -\u003e Void {\n    connection.connect() { result in\n        guard result.success else {\n            guard let error = result.asError else {\n                return callback(\"Error connecting: Unknown Error\")\n            }\n            return callback(\"Error connecting: \\(error)\")\n        }\n        // Build and execute your query here.\n\n        // First build query\n        let query = Select(grades.course, grades.grade, from: grades)\n\n        // Execute query\n        connection.execute(query: query) { result in\n            guard let resultSet = result.asResultSet else {\n                guard let error = result.asError else {\n                    return callback(\"Error executing query: Unknown Error\")\n                }\n                return callback(\"Error executing query: \\(error)\")\n            }\n            var retString = \"\"\n            resultSet.getColumnTitles() { titles, error in\n                guard let titles = titles else {\n                    guard let error = error else {\n                        return callback(\"Error fetching column titles: Unknown Error\")\n                    }\n                    return callback(\"Error fetching column titles: \\(error)\")\n                }\n                for title in titles {\n                    //The column names of the result.\n                    retString.append(\"\\(title.padding(toLength: 35, withPad: \" \", startingAt: 0))\")\n                }\n                retString.append(\"\\n\")\n\n                resultSet.forEach() { row, error in\n                    guard let row = row else {\n                        // A null row means we have run out of results unless we encountered an error\n                        if let error = error {\n                            return callback(\"Error fetching row: \\(error)\")\n                        }\n                        // No error so all rows are processed, make final callback passing result.\n                        return callback(retString)\n                    }\n                    for value in row {\n                        if let value = value {\n                            let valueString = String(describing: value)\n                            retString.append(\"\\(valueString.padding(toLength: 35, withPad: \" \", startingAt: 0))\")\n                        }\n                    }\n                    retString.append(\"\\n\")\n                }\n            }\n        }\n    }\n}\n\nrouter.get(\"/\") {\n  request, response, next in\n\n  grades() {\n    resp in\n    response.send(resp)\n    next()\n  }\n}\n\nKitura.addHTTPServer(onPort: 8080, with: router)\nKitura.run()\n```\n\nNow build the program and run it:\n\n```\n$ swift build\n$ .build/debug/swift-kuery-play\n```\n\nNow open a web page to \u003ca href=\"http://localhost:8080\"\u003ehttp://localhost:8080\u003c/a\u003e and you should see:\n\n```\ncourse                             grade                              \nHow to build your first computer   99                                 \nHow to work at a rock quarry       71      \n```\n\nNow we can change our query line and see different results.\n\nChange the line:\n\n```swift\n      let query = Select(grades.course, grades.grade, from: grades)\n```\n\nto\n\n```swift\n      let query = Select(grades.course, grades.grade, from: grades)\n        .where(grades.grade \u003e 80)\n```\n\nand we should only see grades greater than 80:\n\n```\ncourse                             grade                              \nHow to build your first computer   99                                 \n```\n\nAnother possibility is to use `QueryResult.asRows` that returns the result as an array of dictionaries where each dictionary represents a row of the result with the column title as the key.       \n Change your `grades` function as follows:\n\n```swift\nfunc grades(_ callback: @escaping (String) -\u003e Void) -\u003e Void {\n    connection.connect() { result in\n        guard result.success else {\n            guard let error = result.asError else {\n                return callback(\"Error connecting: Unknown Error\")\n            }\n            return callback(\"Error connecting: \\(error)\")\n        }\n        let query = Select(grades.course, grades.grade, from: grades)\n        connection.execute(query: query) { result in\n            result.asRows() { rows, error in\n                guard let rows = rows else {\n                    guard let error = error else {\n                        return callback(\"Error getting rows: Unknown Error\")\n                    }\n                    return callback(\"Error getting rows: \\(error)\")\n                }\n                var retString = \"\"\n                for row in rows {\n                    for (title, value) in row {\n                        if let value = value {\n                            retString.append(\"\\(title): \\(value) \")\n                        }\n                    }\n                    retString.append(\"\\n\")\n                }\n                return callback(retString)\n            }\n        }\n    }\n}\n```\nAt \u003ca href=\"http://localhost:8080\"\u003ehttp://localhost:8080\u003c/a\u003e you should see:\n\n```\ngrade: 99 course: How to build your first computer\ngrade: 71 course: How to work at a rock quarry  \n```\n## API Documentation\nFor more information visit our [API reference](https://kitura.github.io/Swift-Kuery-PostgreSQL/index.html).\n\n## Community\n\nWe love to talk server-side Swift, and Kitura. Join our [Slack](http://swift-at-ibm-slack.mybluemix.net/) to meet the team!\n\n## License\nThis library is licensed under Apache 2.0. Full license text is available in [LICENSE](https://github.com/Kitura/SwiftKueryPostgreSQL/blob/master/LICENSE.txt)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkitura%2Fswift-kuery-postgresql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkitura%2Fswift-kuery-postgresql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkitura%2Fswift-kuery-postgresql/lists"}