Creates a DynamoDb table with the event store schema.

@param DynamoDbClient $client
@param string         $tableName

@throws EventStoreOperationFailed
503790
public function create(DynamoDbClient $client, string $tableName): void
    {
        try {
            $client->describeTable(['TableName' => $tableName]);
            return;
        } catch (DynamoDbException $e) {
            // table doesn't exist, create it below
        }

        try {
            $client->createTable([
                'TableName'              => $tableName,
                'AttributeDefinitions'   => [
                    ['AttributeName' => self::HASH_KEY_NAME, 'AttributeType' => 'S'],
                    ['AttributeName' => self::RANGE_KEY_NAME, 'AttributeType' => 'N'],
                    ['AttributeName' => self::GSI_EVENT_ID_HASH_KEY_NAME, 'AttributeType' => 'S'],
                ],
                'KeySchema'              => [
                    ['AttributeName' => self::HASH_KEY_NAME, 'KeyType' => 'HASH'],
                    ['AttributeName' => self::RANGE_KEY_NAME, 'KeyType' => 'RANGE'],
                ],
                'GlobalSecondaryIndexes' => [
                    [
                        'IndexName'             => self::GSI_EVENT_ID_NAME,
                        'KeySchema'             => [
                            ['AttributeName' => self::GSI_EVENT_ID_HASH_KEY_NAME, 'KeyType' => 'HASH'],
                        ],
                        'Projection'            => [
                            'ProjectionType' => 'KEYS_ONLY',
                        ],
                        'ProvisionedThroughput' => [
                            'ReadCapacityUnits'  => 2,
                            'WriteCapacityUnits' => 2,
                        ],
                    ],
                ],
                'StreamSpecification'    => [
                    'StreamEnabled'  => true,
                    'StreamViewType' => 'NEW_IMAGE',
                ],
                'ProvisionedThroughput'  => [
                    'ReadCapacityUnits'  => 2,
                    'WriteCapacityUnits' => 2,
                ],
            ]);

            $client->waitUntil('TableExists', ['TableName' => $tableName]);
        } catch (\Throwable $e) {
            throw new EventStoreOperationFailed(
                sprintf(
                    '%s::Unable to create table [%s] in region [%s].',
                    ClassUtils::getShortName($this),
                    $tableName,
                    $client->getRegion()
                ),
                Code::INTERNAL,
                $e
            );
        }
    }
271919
protected function createCreateTable(string $tableName, array $tableConfig): CreateTable
    {
        $createTable = new CreateTable($tableName);
        $primaryKeys = [];

        foreach ($tableConfig as $fieldName => $fieldData) {
            if (isset($fieldData[static::PRIMARY_KEY])) {
                $primaryKeys[] = $fieldName;
            }

            $column = $this->createColumn($fieldData, $fieldName);
            $createTable->addColumn($column);

            if (isset($fieldData[self::UNIQUE_KEY])) {
                $constrain = $this->createUniqueKeyConstraint($fieldData[self::UNIQUE_KEY], $fieldName, $tableName);
                $createTable->addConstraint($constrain);
            }

            if (isset($fieldData[self::FOREIGN_KEY])) {
                $constrain = $this->createForeignKeyConstraint($fieldData[self::FOREIGN_KEY], $fieldName, $tableName);
                $createTable->addConstraint($constrain);
            }
        }

        if (count($primaryKeys)) {
            $createTable->addConstraint(new Constraint\PrimaryKey(...$primaryKeys));
        } else {
            $createTable->addConstraint(new Constraint\PrimaryKey('id'));
        }

        return $createTable;
    }
764049
public Table createTable(CreateTableRequest req) {
        CreateTableResult result = client.createTable(req);
        return new Table(client, req.getTableName(),
            result.getTableDescription());
    }
377172
async def setup(self):
        """"""
        try:
            client = await self.db
            response = await client.list_tables()
            created = False
            # create table if not already created.
            if self.table_name not in response["TableNames"]:
                logger.info("Creating DynamoDB table [{}]".format(self.table_name))
                resp = await client.create_table(**self.table_schema)
                if resp.get("ResponseMetadata", {}).get("HTTPStatusCode") == 200:
                    logger.info("DynamoDB table [{}] successfully created!".format(self.table_name))
                    created = True
            # create control table if not already created.
            if self.control_table_name and self.control_table_name not in response["TableNames"]:
                logger.info("Creating DynamoDB control_table [{}]".format(self.control_table_name))
                resp = await client.create_table(**self.control_table_schema)
                if resp.get("ResponseMetadata", {}).get("HTTPStatusCode") == 200:
                    logger.info("DynamoDB control table [{}] successfully created!".format(self.control_table_name))
                    created = True
            return created
        except Exception as exc:
            logger.error("[DB] Error when setting up DynamoDB.")
            logger.error(exc)
        return False
343012
protected void createTable(TableName tableName, CreateTableRequest request)
          throws IOException {
    try {
      tableAdminClientWrapper.createTable(request);
    } catch (Throwable throwable) {
      throw convertToTableExistsException(tableName, throwable);
    }
  }
184609
public static function checkAndCreateTableByEntityName(ContainerInterface $container, $className, $force = false)
    {
        /** @var Registry $doctrine */
        /** @var Connection $connection */
        /** @var ClassMetadata $classMetadata */
        $doctrine      = $container->get('doctrine');
        $manager       = $doctrine->getManager();
        $schemaTool    = new SchemaTool($doctrine->getManager());
        $connection    = $doctrine->getConnection();
        $schemaManager = $connection->getSchemaManager();
        $classMetadata = $manager->getClassMetadata($className);

        if ($force || !$schemaManager->tablesExist($classMetadata->getTableName())) {

            if ($schemaManager instanceof SqliteSchemaManager) {

                $columns     = array();
                $identifiers = $classMetadata->getIdentifierColumnNames();
                foreach ($classMetadata->getFieldNames() as $fieldName) {
                    $fieldMapping = $classMetadata->getFieldMapping($fieldName);
                    $columnSql    = $fieldMapping["fieldName"];
                    switch ($fieldMapping["type"]) {
                        case 'integer':
                            $columnSql .= " INTEGER ";
                            break;

                        case 'real':
                        case 'double':
                        case 'float':
                            $columnSql .= " REAL ";
                            break;

                        case 'datetime':
                        case 'date':
                        case 'boolean':
                            $columnSql .= " INTEGER ";
                            break;

                        case 'blob':
                        case 'file':
                            $columnSql .= " BLOB ";
                            break;

                        default:
                            $columnSql .= " TEXT ";
                    }

                    // PRIMARY KEY
                    in_array($fieldName, $identifiers) && $columnSql .= "PRIMARY KEY ";
                    $columnSql .= $fieldMapping["nullable"] ? "NULL " : "NOT NULL ";
                    $columns[] = $columnSql;
                }
                $sql       = 'CREATE TABLE IF NOT EXISTS ' . $classMetadata->getTableName() . '( ' . implode(",\n", $columns) . ')';
                $statement = $connection->query($sql);
            } else {
                $schemaTool->updateSchema(array($classMetadata), true);
            }
        }
    }
793621
function init(\CharlotteDunois\Livia\Client $client): \React\Promise\ExtendedPromiseInterface {
        $this->client = $client;
        $this->attachListeners();
        
        return $this->db->execute('CREATE TABLE IF NOT EXISTS settings (guild VARCHAR(20) NOT NULL, settings TEXT NOT NULL, PRIMARY KEY (guild))')
            ->then(function () {
                return $this->db->execute('SELECT * FROM settings')->then(function (\Plasma\StreamQueryResultInterface $result) {
                    return $result->all()->then(function (\Plasma\QueryResultInterface $result) {
                        $rows = $result->getRows();
                        
                        foreach($rows as $row) {
                            $this->loadRow($row);
                        }
                        
                        if($this->settings->has('global')) {
                            return null;
                        }
                        
                        return $this->create('global')->then(function () {
                            return null;
                        });
                    });
                });
            });
    }
723609
protected function tableExists($tableName)
    {
        $found    = false;
        $iterator = $this->dynamoDb->getClient()->getIterator('ListTables');
        foreach ($iterator as $table) {
            if ($table === $tableName) {
                $found = true;
            }
        }

        return $found;
    }
174521
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(event.getTableName()), schema);
        List<SchemaStatement> statements = schema.items().map(SchemaItem::createStatement).collect(Collectors.toList());
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statements.stream().map(SchemaStatement::getQueryString).collect(Collectors.joining("\n\t")));
        }
        statements.forEach(session::execute);
    }
1202070
void deleteRow(String storeName, Map<String, AttributeValue> key) {
        String tableName = storeToTableName(storeName);
        m_logger.debug("Deleting row from table {}, key={}", tableName, DynamoDBService.getDDBKey(key));
        
        Timer timer = new Timer();
        boolean bSuccess = false;
        for (int attempts = 1; !bSuccess; attempts++) {
            try {
                m_ddbClient.deleteItem(tableName, key);
                if (attempts > 1) {
                    m_logger.info("deleteRow() succeeded on attempt #{}", attempts);
                }
                bSuccess = true;
                m_logger.debug("Time to delete table {}, key={}: {}",
                               new Object[]{tableName, DynamoDBService.getDDBKey(key), timer.toString()});
            } catch (ProvisionedThroughputExceededException e) {
                if (attempts >= m_max_commit_attempts) {
                    String errMsg = "All retries exceeded; abandoning deleteRow() for table: " + tableName;
                    m_logger.error(errMsg, e);
                    throw new RuntimeException(errMsg, e);
                }
                m_logger.warn("deleteRow() attempt #{} failed: {}", attempts, e);
                try {
                    Thread.sleep(attempts * m_retry_wait_millis);
                } catch (InterruptedException ex2) {
                    // ignore
                }
            }
        }
    }
65641
private function createClientsView(Connection $connection, DatabaseSchemaInterface $schema)
    {
        $view             = $schema->getClientsView();
        $scopes           = $schema->getClientsViewScopesColumn();
        $redirectUris     = $schema->getClientsViewRedirectUrisColumn();
        $clientsScopes    = $schema->getClientsScopesTable();
        $clientsUris      = $schema->getRedirectUrisTable();
        $clients          = $schema->getClientsTable();
        $clientsClientId  = $schema->getClientsIdentityColumn();
        $clScopesClientId = $schema->getClientsScopesClientIdentityColumn();
        $clUrisClientId   = $schema->getRedirectUrisClientIdentityColumn();
        $urisValue        = $schema->getRedirectUrisValueColumn();
        $scopesScopeId    = $schema->getScopesIdentityColumn();
        $sql              = <<< EOT
CREATE VIEW {$view} AS
    SELECT
      c.*,
      array_remove(array_agg(s.{$scopesScopeId}), NULL) AS {$scopes},
      array_remove(array_agg(u.{$urisValue}), NULL)     AS {$redirectUris}
    FROM {$clients} AS c
      LEFT JOIN {$clientsScopes} AS s ON c.{$clientsClientId} = s.{$clScopesClientId}
      LEFT JOIN {$clientsUris}   AS u ON c.{$clientsClientId} = u.{$clUrisClientId}
    GROUP BY c.{$clientsClientId};
EOT;
        $connection->exec($sql);
    }
744636
public static function for_table($table_name, $connection_name = parent::DEFAULT_CONNECTION)
        {
            self::_setupDb($connection_name);

            return new self($table_name, [], $connection_name);
        }
345047
public function insertRecord($tableName, array $data) {
	
		$data = array_change_key_case($data, CASE_LOWER);
	
		if(!$this->tableStructureCache || !array_key_exists($tableName, $this->tableStructureCache) || empty($this->tableStructureCache[$tableName])) {
			$this->fillTableStructureCache($tableName);
		}
	
		if(!array_key_exists($tableName, $this->tableStructureCache)) {
			throw new \PDOException(sprintf("Table '%s' not found.", $tableName));
		}
	
		$attributes = array_keys($this->tableStructureCache[$tableName]);
		$columns = $this->tableStructureCache[$tableName];
	
		$names = [];
		$values = [];
	
		foreach($attributes as $attribute) {
	
			if (array_key_exists($attribute, $data)) {
				$names[]	= $columns[$attribute]['columnName'];
				$values[]	= $data[$attribute];
			}
	
		}
	
		// nothing to do
	
		if(!count($names)) {
			return null;
		}
	
		$valuePlaceholders = implode(', ', array_fill(0, count($values), '?'));
	
		// append create timestamp when applicable
	
		if(
			in_array(static::CREATE_FIELD, $attributes) &&
			!in_array(static::CREATE_FIELD, array_keys($data))
		) {
					
			// for compatibility purposes get the real column name
				
			$names[] = $columns[static::CREATE_FIELD]['columnName'];
			$valuePlaceholders .= ', NOW()';
		}

		// prime and execute statement

        if(
            $this->primeQuery(
				sprintf("
                        INSERT INTO
                            %s
                        (%s%s%s)
                        VALUES
                        (%s)
                        ",
                    static::QUOTE_CHAR . $tableName . static::QUOTE_CHAR,
                    static::QUOTE_CHAR, implode(static::QUOTE_CHAR . ', ' . static::QUOTE_CHAR, $names), static::QUOTE_CHAR,
                    $valuePlaceholders
                ),
                $values
    		)->execute()
		) {
			return $this->connection->lastInsertId();
		}

		throw new \PDOException(vsprintf('ERROR: %s, %s, %s', $this->statement->errorInfo()));
	
	}
1042527
private TableDDL createTableDDL(String tableName) {
        TableMetadata tableMetadata = _keyspace.getKeyspaceMetadata().getTable(tableName);
        String rowKeyColumnName = tableMetadata.getPrimaryKey().get(0).getName();
        String timeSeriesColumnName = tableMetadata.getPrimaryKey().get(1).getName();
        String valueColumnName = tableMetadata.getColumns().get(2).getName();

        return new TableDDL(tableMetadata, rowKeyColumnName, timeSeriesColumnName, valueColumnName);
    }
745260
public function onClientError(ClientErrorEvent $event)
    {
        $conn = $event->getConnection();
        $e = $event->getException();

        echo "connection error occurred: " . $e->getMessage() . PHP_EOL;
    }
584760
@SneakyThrows
    public AmazonDynamoDB createAmazonDynamoDb(final AbstractDynamoDbProperties props) {
        if (props.isLocalInstance()) {
            LOGGER.debug("Creating DynamoDb standard client with endpoint [{}] and region [{}]",
                props.getEndpoint(), props.getRegion());
            val endpoint = new AwsClientBuilder.EndpointConfiguration(
                props.getEndpoint(), props.getRegion());
            return AmazonDynamoDBClientBuilder.standard()
                .withEndpointConfiguration(endpoint)
                .build();
        }

        val provider = ChainingAWSCredentialsProvider.getInstance(props.getCredentialAccessKey(),
            props.getCredentialSecretKey(), props.getCredentialsPropertiesFile());

        LOGGER.trace("Creating DynamoDb client configuration...");
        val cfg = AmazonClientConfigurationBuilder.buildClientConfiguration(props);

        LOGGER.debug("Creating DynamoDb client instance...");
        val clientBuilder = AmazonDynamoDBClientBuilder
            .standard()
            .withClientConfiguration(cfg)
            .withCredentials(provider);

        val region = StringUtils.defaultIfBlank(props.getRegionOverride(), props.getRegion());

        if (StringUtils.isNotBlank(props.getEndpoint())) {
            LOGGER.trace("Setting DynamoDb client endpoint [{}]", props.getEndpoint());
            clientBuilder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(props.getEndpoint(), region));
        }

        if (StringUtils.isNotBlank(region)) {
            LOGGER.trace("Setting DynamoDb client region [{}]", props.getRegion());
            clientBuilder.withRegion(region);
        }
        return clientBuilder.build();
    }
848267
public function describe(DynamoDbClient $client, string $tableName): string
    {
        try {
            $result = $client->describeTable(['TableName' => $tableName]);
            return json_encode($result->toArray(), JSON_PRETTY_PRINT);
        } catch (\Throwable $e) {
            throw new SchedulerOperationFailed(
                sprintf(
                    '%s::Unable to describe table [%s] in region [%s].',
                    ClassUtils::getShortName($this),
                    $tableName,
                    $client->getRegion()
                ),
                Code::INTERNAL,
                $e
            );
        }
    }