Skip to content

Instantly share code, notes, and snippets.

@seaders
Created March 13, 2015 14:07
Show Gist options
  • Select an option

  • Save seaders/697e59ecb0e4b92d3715 to your computer and use it in GitHub Desktop.

Select an option

Save seaders/697e59ecb0e4b92d3715 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2;
using Amazon;
using System;
using Amazon.Runtime;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.DataModel;
public class SMDynamoDBSetup : Singleton<SMDynamoDBSetup>
{
public readonly string USER_KEY = "userId";
public readonly string LEADERBOARD_KEY = "leaderboardId";
public readonly string COUNTRY_KEY = "country";
public readonly string DATA_KEY = "data";
public readonly string SCORE_KEY = "score";
public static readonly string GLOBAL_SCORE_INDEX = "ScoreIndex";
public static readonly string TABLE_NAME = "GameLevelLeaderboard";
public static readonly List<string> COUNTRIES = new List<string> {"Ireland", "England", "USA", "Germany", "Portugal", "France"};
public static readonly List<string> PLAYERS = new List<string> {"seaders", "slicko", "shrine", "pod", "wowy", "play2lose", "ben@ben", "xaikira"};
public static readonly List<string> LEVELS = new List<string> {"outrun::level1", "outrun::level2", "outrun::level3", "outrun::level4", "outrun::level5"};
private AmazonDynamoDBClient _dynamoClient;
public AmazonDynamoDBClient dynamoClient {
get { return _dynamoClient; }
set { _dynamoClient = value; }
}
public void CreateTable()
{
// Attribute definitions
List<AttributeDefinition> attributeDefinitions = new List<AttributeDefinition>()
{
{new AttributeDefinition {AttributeName = USER_KEY, AttributeType = "S"}},
{new AttributeDefinition {AttributeName = LEADERBOARD_KEY, AttributeType = "S"}},
{new AttributeDefinition {AttributeName = SCORE_KEY, AttributeType = "N"}}
};
// Key schema for table
List<KeySchemaElement> tableKeySchema = new List<KeySchemaElement>() {
{
new KeySchemaElement {
AttributeName= USER_KEY,
KeyType = "HASH"
}
},
{
new KeySchemaElement {
AttributeName = LEADERBOARD_KEY,
KeyType = "RANGE"
}
}
};
// Initial provisioned throughput settings for the indexes
ProvisionedThroughput ptIndex = new ProvisionedThroughput
{
ReadCapacityUnits = 1L,
WriteCapacityUnits = 1L
};
// GlobalScoreIndex
GlobalSecondaryIndex GlobalScoreIndex = new GlobalSecondaryIndex()
{
IndexName = GLOBAL_SCORE_INDEX,
ProvisionedThroughput = ptIndex,
KeySchema = {
new KeySchemaElement {
AttributeName = LEADERBOARD_KEY,
KeyType = "HASH"
},
new KeySchemaElement {
AttributeName = SCORE_KEY,
KeyType = "RANGE"
}
},
Projection = new Projection
{
ProjectionType = "ALL"
}
};
CreateTableRequest createTableRequest = new CreateTableRequest
{
TableName = TABLE_NAME,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = (long)1,
WriteCapacityUnits = (long)1
},
AttributeDefinitions = attributeDefinitions,
KeySchema = tableKeySchema,
GlobalSecondaryIndexes = { GlobalScoreIndex }
};
Debug.Log("Creating table " + TABLE_NAME + "...");
dynamoClient.CreateTableAsync(
createTableRequest,
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
Debug.Log(result.Response);
},
null
);
}
public void LoadData()
{
Debug.Log("Loading data into table " + TABLE_NAME + "...");
System.Random rnd = new System.Random();
int score;
string country;
foreach(string player in PLAYERS)
{
foreach(string level in LEVELS)
{
score = rnd.Next(1000, 1500);
country = COUNTRIES[ rnd.Next(COUNTRIES.Count) ];
putItem(player, level, country, score, "ghostId::...");
Debug.Log("adding " + player + " in " + country + " for " + level + ", " + score);
}
}
}
private void putItem(string userId, string leaderboardId, string country, int score, string data)
{
Dictionary<String, AttributeValue> item = new Dictionary<string, AttributeValue>
{
{ USER_KEY, new AttributeValue { S = userId } },
{ LEADERBOARD_KEY, new AttributeValue { S = leaderboardId } },
{ COUNTRY_KEY, new AttributeValue { S = country } },
{ SCORE_KEY, new AttributeValue { N = score.ToString() } },
{ DATA_KEY, new AttributeValue { S = data } }
};
try
{
dynamoClient.PutItemAsync(
new PutItemRequest
{
TableName = TABLE_NAME,
Item = item
},
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
Debug.Log("success " + result.Response);
},
null
);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
public void DescribeTable()
{
dynamoClient.DescribeTableAsync (
new DescribeTableRequest
{
TableName = TABLE_NAME
},
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
DescribeTableResponse response = result.Response as DescribeTableResponse;
Debug.Log(response.Table.ItemCount);
},
null
);
}
public void FriendRowsQuery(string leaderboardId)
{
BatchGetItemRequest request = new BatchGetItemRequest
{
RequestItems = new Dictionary<string, KeysAndAttributes>()
{
{
TABLE_NAME,
new KeysAndAttributes
{
Keys = new List<Dictionary<string, AttributeValue>>()
{
new Dictionary<string, AttributeValue>()
{
{ USER_KEY, new AttributeValue { S = PLAYERS[0] } },
{ LEADERBOARD_KEY, new AttributeValue { S = leaderboardId } }
},
new Dictionary<string, AttributeValue>()
{
{ USER_KEY, new AttributeValue { S = PLAYERS[1] } },
{ LEADERBOARD_KEY, new AttributeValue { S = leaderboardId } }
}
}
}
}
}
};
dynamoClient.BatchGetItemAsync(
request,
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
BatchGetItemResponse response = result.Response as BatchGetItemResponse;
foreach(KeyValuePair<string, List< Dictionary<string, AttributeValue> > > tableResponse in response.Responses)
{
Debug.Log("Items retrieved from table " + tableResponse.Key);
logResults(tableResponse.Value);
}
},
null
);
}
public void QueryRows(string leaderboardId, string country)
{
Debug.Log("\n***********************************************************\n");
Debug.Log("Querying index " + GLOBAL_SCORE_INDEX + "...");
QueryRequest queryRequest = new QueryRequest
{
TableName = TABLE_NAME,
IndexName = GLOBAL_SCORE_INDEX,
ScanIndexForward = false
};
Dictionary<string, Condition> keyConditions = new Dictionary<String, Condition>();
Dictionary<string, Condition> queryFilters = new Dictionary<String, Condition>();
keyConditions.Add(
SCORE_KEY,
new Condition
{
ComparisonOperator = "GT",
AttributeValueList = { new AttributeValue { N = "0" } }
}
);
keyConditions.Add(
LEADERBOARD_KEY,
new Condition
{
ComparisonOperator = "EQ",
AttributeValueList = { new AttributeValue { S = leaderboardId } }
}
);
if(null != country)
{
queryFilters.Add (
COUNTRY_KEY,
new Condition
{
ComparisonOperator = "EQ",
AttributeValueList = { new AttributeValue { S = country } }
}
);
}
queryRequest.QueryFilter = queryFilters;
queryRequest.KeyConditions = keyConditions;
dynamoClient.QueryAsync(
queryRequest,
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
logResults( (result.Response as QueryResponse).Items );
},
null
);
}
private void logResults(List< Dictionary<string, AttributeValue> > items)
{
foreach(Dictionary<string, AttributeValue> item in items)
{
Debug.Log(
item[USER_KEY].S + ", " +
item[LEADERBOARD_KEY].S + ", " +
item[COUNTRY_KEY].S + ", " +
item[SCORE_KEY].N + ", " +
item[DATA_KEY].S
);
}
}
public void DeleteTable()
{
Debug.Log("Deleting table " + TABLE_NAME + "...");
dynamoClient.DeleteTableAsync(
new DeleteTableRequest { TableName = TABLE_NAME },
(AmazonServiceResult result) =>
{
if(null != result.Exception)
{
Debug.LogException(result.Exception);
return;
}
Debug.Log(result.Response);
},
null
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment