Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Changelog.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@

# 11.3.0-beta
[added] Initial public beta release of the SDK. For more information visit [Firebase Data Connect](https://firebase.google.com/products/data-connect)

154 changes: 1 addition & 153 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,160 +16,8 @@ Instructions for [Swift Package Manager](https://swift.org/package-manager/) sup
found in the [SwiftPackageManager.md](SwiftPackageManager.md) Markdown file.

## Getting Started
Firebase Data Connect is in Private Preview at no cost for a limited time. Sign up the program at https://firebase.google.com/products/data-connect.

Once you are selected as an allowlist member, you should be able to create a Cloud SQL instance through Firebase Data Connect console.

Here's a quick rundown of steps to get you started. Learn more about details at the official [Getting Started documentation](https://firebase.google.com/docs/data-connect/quickstart).

### 1. Create a new Data Connect service and Cloud SQL instance.
* Go to Firebase Console and select Firebase Data Connect from the Left Navigation bar to create a new Data Connect service and a Cloud SQL instance. You have to be in Blaze plan and you can view the details of pricing at https://firebase.google.com/pricing.
* Select us-central1 region if you want to try out vector search with Data Connect later.
* Your Cloud SQL instance is now to be provisioned, you can view and manage the instance at the Google Cloud console.

### 2. Setup your iOS app and [initialize Firebase](https://firebase.google.com/docs/ios/setup)

#### The following steps will guide you to setup your schema and create query operation that you need for your app. The toolings below will help you to test out your query with dummy data and once you are happy with your query, the tools will help generate client code for that query so you can call directly from your app.


### 3. Set up [Firebase CLI](https://firebase.google.com/docs/cli)

* If you already have CLI, make sure you always update to the latest version
```
npm install -g firebase-tools
```

### 4. Set up VSCode
You will need VS Code and its Firebase extension (VS Code extension) to automatically generate Swift code for your queries.
* Install VS Code
* Download the [extension](https://firebasestorage.googleapis.com/v0/b/firemat-preview-drop/o/vsix%2Ffirebase-vscode-latest.vsix?alt=media) and drag it into the "Extensions" in the Left Navigation bar for installation. Keep in mind double clicking the file won't install.
* Create a fdc folder where you like to have firebase data connect configuration.
```
mkdir fdc
```
* Open VS Code from folder you just created
* Select the Firebase icon on the left and login
* Click on "Run firebase init" button

* Select the first option of Data Connect
* Enter/Select the project, service and database ID you setup on the console
* Enter to select the default connector ID and complete the rest of the process

### 5. Set up generated SDK location
In the connector.yaml file, add the following code to enable swift code to be generated.

```
swiftSdk:
outputDir: "../swift-generated/"
package: "User"
```
* You should see swift code is generated inside the ../swift-generated/User/ folder

### 6. Create a schema and generate some dummy data
* In the schema.gql file, uncomment the schema
```
type User @table(key: "uid") {
uid: String!
name: String!
address: String!
}
```
* On top of the schema User, an "Add data" button start showing up, click on it to generate a User_insert.gql file
* Fill out the fields and click on Run button to run the query to add a user dummy data for testing

### 7. Deploy your schema
* To deploy your schema, you will need your Cloud SQL instance to be ready. You can view the instance at the Cloud Cloud console.
* Select the Firebase icon on the left and Click on the "Deploy all" button to deploy all the schema and operations to backend.
* You can now see your schemas on the Firebase Console.

### 8. Set up a mutation
In the mutations.gql file, uncomment the "CreateUser" query.
* In the CONFIGURATION -> VARIABLES, enter
```
{
"name" : "dummy_name",
"address" : "dummy_address"
}
```
* In the CONFIGURATION -> AUTHENTICATION, select Run as "Authenticated".
* Click on the "Run" button above the query.
* You should see your dummy data is added.
* Select the Firebase icon on the left and Click on the "Deploy all" button to deploy all the schema and operations to backend.
* As you see this operation needs authentication, so you will need to be authenticated with Firebase Authentication in your client app when you call this operation in iOS app.

#### At this point, you have the code generated for the queries you need for your app. Now let's see how you can use the generated query code in your iOS app:

### 9. Adding the generated package to your app project
* Go to File -> Add Package Dependencies -> Add Local
* Navigate to the generated folder and select the "swift-generated/User" folder (You should see a Package.swift file in it).

### 10. Calling the generated code from your app
```
import FirebaseDataConnect
import Users //change this to the name of your generated package

func executeFDCCreateUserQuery() {
Task {
do {
let result = try await DataConnect.defaultConnectorClient.createUserMutationRef(name: "dummyUserName", address: "dummyUserAddress").execute()
} catch {
}
}
}

```




## Development

To develop Firebase software in this repository, ensure that you have at least
the following software:

* Xcode 15.2 (or later)

### Swift Package Manager
* To enable test schemes: `./scripts/setup_spm_tests.sh`
* `open Package.swift` or double click `Package.swift` in Finder.
* Xcode will open the project
* Choose a scheme for a library to build or test suite to run
* Choose a target platform by selecting the run destination along with the scheme

### Code Formatting

To ensure that the code is formatted consistently, run the script
[./scripts/check.sh](https://github.com/firebase/firebase-ios-sdk/blob/main/scripts/check.sh)
before creating a pull request (PR).

GitHub Actions will verify that any code changes are done in a style-compliant
way. Install `clang-format` and `mint`:

```console
brew install clang-format@19
brew install mint
```

### Running Unit Tests

Select a scheme and press Command-u to build a component and run its unit tests.

### Running Sample Apps
To run the sample apps and integration tests, you'll need a valid
`GoogleService-Info.plist
` file. The Firebase Xcode project contains dummy plist
files without real values, but they can be replaced with real plist files. To get your own
`GoogleService-Info.plist` files:

1. Go to the [Firebase Console](https://console.firebase.google.com/)
2. Create a new Firebase project, if you don't already have one
3. For each sample app you want to test, create a new Firebase app with the sample app's bundle
identifier (e.g., `com.google.Database-Example`)
4. Download the resulting `GoogleService-Info.plist` and add it to the Xcode project.

### Coverage Report Generation

For coverage report generation instructions, see [scripts/code_coverage_report/README](scripts/code_coverage_report/README.md) Markdown file.
Learn how to develop on Data Connect - [Quick Start](https://firebase.google.com/docs/data-connect/quickstart).

## Contributing

Expand Down
4 changes: 4 additions & 0 deletions Sources/DataConnect.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public class DataConnect {

// MARK: Static Creation

/// Returns an instance of DataConnect matching the parameters.
/// If a matching instance is found that is returned, otherwise a new instance is created.
public class func dataConnect(app: FirebaseApp? = FirebaseApp.app(),
connectorConfig: ConnectorConfig,
settings: DataConnectSettings = DataConnectSettings(),
Expand Down Expand Up @@ -108,6 +110,7 @@ public class DataConnect {

// MARK: Operations

/// Returns a query ref matching the name and variables.
public func query<ResultData: Decodable,
Variable: OperationVariable>(name: String,
variables: Variable,
Expand All @@ -119,6 +122,7 @@ public class DataConnect {
return operationsManager.queryRef(for: request, with: resultsDataType, publisher: publisher)
}

/// Returns a Mutation Ref matching the name and specified variables.
public func mutation<ResultData: Decodable,
Variable: OperationVariable>(name: String,
variables: Variable,
Expand Down
12 changes: 7 additions & 5 deletions Sources/DataConnectError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,24 @@

import Foundation

/// Represents an error returned by the DataConnect service
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum DataConnectError: Error {
// no firebase app specified. configure not complete
/// no firebase app specified. configure not complete
case appNotConfigured

/// failed to configure gRPC
case grpcNotConfigured

// failed to decode results from server
/// failed to decode results from server
case decodeFailed

// uuid string length is not correct.
/// Invalid uuid format during encoding / decoding of data
case invalidUUID

// date components specified to initialize LocalDate are invalid
/// date components specified to initialize LocalDate are invalid
case invalidLocalDateFormat

// timestamp components specified to initialize Timestamp are invalid
/// timestamp components specified to initialize Timestamp are invalid
case invalidTimestampFormat
}
1 change: 1 addition & 0 deletions Sources/MutationRef.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ struct MutationRequest<Variable: OperationVariable>: OperationRequest {
}
}

/// Represents a predefined graphql mutation identified by name and variables.
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public class MutationRef<ResultData: Decodable, Variable: OperationVariable>: OperationRef {
private var request: any OperationRequest
Expand Down
61 changes: 50 additions & 11 deletions Sources/QueryRef.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,18 @@ import Foundation
import Combine
import Observation

/// The type of publisher to use for the Query Ref
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public enum ResultsPublisherType {
case auto // automatically determine ObservableQueryRef
case observableObject // pre-iOS 17 ObservableObject
case observableMacro // iOS 17+ Observation framework
/// automatically determine ObservableQueryRef.
/// Tries to pick the iOS 17+ Observation but falls back to ObservableObject
case auto

/// pre-iOS 17 ObservableObject
case observableObject

/// iOS 17+ Observation framework
case observableMacro
}

@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
Expand Down Expand Up @@ -122,10 +129,18 @@ public protocol ObservableQueryRef: QueryRef {
var lastError: DataConnectError? { get }
}

// QueryRef class used with ObservableObject protocol
// data: Published variable that contains bindable results of the query.
// lastError: Published variable that contains DataConnectError if last fetch had error.
// If last fetch was successful, this variable is cleared
/// QueryRef class compatible with ObservableObject protocol
///
/// When the requested publisher is an ObservableObject, the returned query refs will be instances
/// of this class
///
/// This class cannot be instantiated directly. To get an instance, call the
/// ``DataConnect/dataConnect(...)`` function
///
/// This class publishes two vars
/// - ``data``: Published variable that contains bindable results of the query.
/// - ``lastError``: Published variable that contains ``DataConnectError`` if last fetch had error.
/// If last fetch was successful, this variable is cleared
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public class QueryRefObservableObject<
ResultData: Decodable,
Expand Down Expand Up @@ -161,27 +176,43 @@ public class QueryRefObservableObject<

// ObservableQueryRef implementation

/// data published by query of type `ResultData`
@Published public private(set) var data: ResultData?

/// Error thrown if error occurs during execution of query. If the last fetch was successful the
/// error is cleared
@Published public private(set) var lastError: DataConnectError?

// QueryRef implementation

/// Executes the query and returns `ResultData`. This will also update the published `data`
/// variable
public func execute() async throws -> OperationResult<ResultData> {
let result = try await baseRef.execute()
return result
}

/// Returns the underlying results publisher.
/// Use this function ONLY if you plan to use the Query Ref outside of SwiftUI context - (UIKit,
/// background updates,...)
public func subscribe() async throws
-> AnyPublisher<Result<ResultData, DataConnectError>, Never> {
return await baseRef.subscribe()
}
}

// QueryRef class compatible with the Observation framework introduced in iOS 17
// data: Published variable that contains bindable results of the query.
// lastError: Published variable that contains DataConnectError if last fetch had error.
// If last fetch was successful, this variable is cleared
/// QueryRef class compatible with the Observation framework introduced in iOS 17
///
/// When the requested publisher is an ObservableMacri, the returned query refs will be instances
/// of this class
///
/// This class cannot be instantiated directly. To get an instance, call the
/// ``DataConnect/dataConnect(...)`` function
///
/// This class publishes two vars
/// - ``data``: Published variable that contains bindable results of the query.
/// - ``lastError``: Published variable that contains ``DataConnectError`` if last fetch had error.
/// If last fetch was successful, this variable is cleared
@available(macOS 14, iOS 17, tvOS 17, watchOS 10, *)
@Observable
public class QueryRefObservation<
Expand Down Expand Up @@ -221,17 +252,25 @@ public class QueryRefObservation<

// ObservableQueryRef implementation

/// data published by query of type `ResultData`
public private(set) var data: ResultData?

/// Error thrown if error occurs during execution of query. If the last fetch was successful the
/// error is cleared
public private(set) var lastError: DataConnectError?

// QueryRef implementation

/// Executes the query and returns `ResultData`. This will also update the published `data`
/// variable
public func execute() async throws -> OperationResult<ResultData> {
let result = try await baseRef.execute()
return result
}

/// Returns the underlying results publisher.
/// Use this function ONLY if you plan to use the Query Ref outside of SwiftUI context - (UIKit,
/// background updates,...)
public func subscribe() async throws
-> AnyPublisher<Result<ResultData, DataConnectError>, Never> {
return await baseRef.subscribe()
Expand Down
Loading