Objective-C in the Cloud

PGCConnection Class Reference

Declared inPGCKit/PGCConnection.h
Base classNSObject
Guides

Overview

PGCConnection represents a connection to the database of the running instance of the cloud application. Typically one running instance has one connection.

Connect to Database

To use the cloud application's database you first create an instance object of PGCConnection and then connect it to the database:

NSError *error = nil;
NSString *connectionString = @"YOUR_CONNECTION_STRING";
PGCConnection *connection = [PGCConnection newWithConnectionString:connectionString];
if(![connection connectAndGetError:&error]) {
   // Do error handling
}

Executing Commands/Queries

One an instance object of PGCConnectionis connected to the database you can execute commands on it by simply using -executeQuery:withArguments:error:. This includes SELECT.

NSError *error = nil;
NSString *query = @"SELECT name, age FROM person WHERE name = $1 AND age = $2";
PGCResult *result = [connection execute:query withArguments:@[@"Chris", @25] error:&error];
if(result == nil) {
   // Do error handling
}

You then can read the returned instance object to introspect the result. -initWithConnectionString: is the designated initializer.

Notes about Thread-safety

PGCConnection and PGCResult are (by design) not thread-safe. You should only ever use instances of those classes on the thread that created them. However, if you want to use an instance of PGCConnection on a different thread you can do so by using the -perform*:-methods. Their default behavior is as follows:

  • -performBlock: Executes the given block synchronously (yes: synchronously) on an internal queue that is managed by the connection instance.
  • -performBlockAndWait: Executes the given block synchronously (yes: synchronously) on an internal queue that is managed by the connection instance.
  • -performTransaction: Wraps the given block in an SQL-transaction and executes the block synchronously.

PGCConnection has a property called performBlockExecutesAsynchonously. When set to YES (default is NO) then -performBlock: will execute the block asynchronously. This is kinda awkward but due to historical reasons it works this way. At some point in the future the default value of performBlockExecutesAsynchonously will be changed to YES. If you want to make your apps future proof set this value explicitly right after you have created the connection object.

Transactions

Transactions work like this:

PGCConnection *connection = [self defaultDatabaseConnection];
[connection performTransaction:^(BOOL *rollback) {
   // Everything done here is wrapped in an SQL transaction.
   // If you do not touch *rollback then everything you do in this
   // block will be committed. If you set *rollback to YES then
   // your changes (if any) will be rolled back.
   BOOL success = [self doSomethingWithConnection:connection];
   *rollback = !success;
}];

Internally PGCConnection is merely using -beginTransaction, -commitTransaction and -rollbackTransaction. Transactions cannot be nested.

Subclassing

There should be no reason to subclass PGCConnection. However, -initWithConnectionString: is the designated initializer.

Tasks

Creating a Connection Object

+newWithConnectionString:
-initWithConnectionString:

Connecting

-connectAndGetError:
-close
-isConnected

Commands

-beginTransaction
-commitTransaction
-rollbackTransaction
-execute:withArguments:error:

Performing Block Operations

-performBlock:
-performBlockAndWait:
-performTransaction:

Class Methods

newWithConnectionString:

Returns additional global information.

+ (instancetype)newWithConnectionString:(NSString *)connectionString

Parameters

connectionString
A PostgreSQL connection string

Discussion

Returns a newly allocated and initialized instance object. The connection string you pass should be obtained from Objective-Cloud Connect. For a detailed documentation of the format refer to the documentation of PostgreSQL's libpq.

Instance Methods

beginTransaction

Opens a new transaction.

- (BOOL)beginTransaction

Discussion

Opens a new transaction. You have to close the transaction with -commitTransaction or -rollbackTransaction.

close

Closes a connected connection.

- (void)close

Discussion

Closes a connection that has been previously connected with -connectAndGetError:.

commitTransaction

Commits a transaction.

- (BOOL)commitTransaction

Discussion

Commits a previously with [-beginTransaction](#i_beginTransaction] begun transaction.

If an error occurred, the return value is NO, otherwise YES.

connectAndGetError:

Connects a connection to the database.

- (BOOL)connectAndGetError:(NSError **)outError;

Parameters

outError
Out parameter: Set, if an error occurs

Discussion

Connects the connection to the database specified by the connection string passed at object initialization.

Closes a connection that has been previously connected with -connectAndGetError:.

If the connection fails, the return value is NO and error is set to an instance of NSErrorwith information about the reason of failing, otherwise the return value is YES.

If the connection is already established, the behavior is undefined.

execute:withArguments:error:

Executes a command on the database.

- (PGCResult *)execute:(NSString *)command withArguments:(NSArray *)arguments error:(NSError **)outError

Parameters

command
A PostgreSQL command
arguments
An array of arguments for the command
outError
Out parameter: Set, if an error occurs

Discussion

This method supports prepared statements: You can use placeholders inside the command string that are filled in from the arguments array. The placeholder has to be of the format $n wherein n is a positiv integral number starting at 1.

NSError *error = nil;
NSString *query = @"SELECT name, age FROM person WHERE name = $1 AND age = $2";
PGCResult *result = [connection execute:query withArguments:@[@"Chris", @25] error:&error];

You should never use Cocoa's methods to build a command string, i. e. stringWithFormat: (NSString). Doing so you have to pay great attention to prevent SQL injection attacks. Prepared statements take care of SQL injection themselves.

The arguments array can contain instances of NSString, NSNumber (for wrapping BOOLs, ints, floats), NSDate, NSNull (for NULL values) and NSData.

If the execution failed because of an error, the return value is nil and outError contains an instance of NSError that describes the problem. You can pass NULL for outError, if you are not interested in the reason.

initWithConnectionString:

Returns additional global information.

- (instancetype)initWithConnectionString:(NSString *)connectionString

Parameters

connectionString
A PostgreSQL connection string

Discussion

See +newWithConnectionString:.

isConnected

Returns, whether the connection is connected.

- (BOOL)isConnected

Discussion

Return YES, if the receiver is already connected to a database, otherwise NO.

rollbackTransaction

Rolls back a transaction.

- (BOOL)rollbackTransaction

Discussion

Rolls back a previously with [-beginTransaction](#i_beginTransaction] begun transaction.

If an error occurred, the return value is NO, otherwise YES.

performBlock:

By default, executes the given block synchronously.

- (void)performBlock:(void(^)(void))block

Discussion

This method executes block on an internal queue managed by the connection instance. Use this method whenever you want to interact with the connection object from different threads.

performBlockAndWait:

By default, executes the given block synchronously.

- (void)performBlockAndWait:(void(^)(void))block

Discussion

This method executes block on an internal queue managed by the connection instance. Use this method whenever you want to interact with the connection object from different threads.

performTransaction:

Wraps the block in an SQL-transaction and executes the block synchronously.

- (void)performTransaction:(void(^)(BOOL *rollback))block

Discussion

This method executes block on an internal queue managed by the connection instance. Use this method whenever you want to use transactions from different threads.