GithubHelp home page GithubHelp logo

kitar / laravel-dynamodb Goto Github PK

View Code? Open in Web Editor NEW
178.0 178.0 26.0 108 KB

A DynamoDB based Eloquent model and Query builder for Laravel.

License: MIT License

PHP 100.00%
aws dynamodb eloquent laravel php

laravel-dynamodb's Introduction

👋こんにちは, I’m Satoshi Kita.

Web Engineer and Product Developer. Building web apps in a small company.

Twitter Follow

Now
  • 🚀 I run SlidePack at Qitar LLC.
  • ✨ I develop AI powered apps and offer advice on leveraging AI to enhance our customers' businesses.
  • 💻 I also develop and run various business apps and web services for our customers.
  • 🌱 I maintain kitar/laravel-dynamodb.
  • 🚀 Qitar LLCでSlidePackを運営しています
  • ✨ AIを活用したアプリの開発や、AIを業務活用するアドバイスを提供しています
  • 💻 お客さん向けの業務システムやWebサービスも色々運営しています
  • 🌱 kitar/laravel-dynamodb をメンテしています
Before
  • 🤝 Founded Qitar LLC to expand SlidePack and other products, which I had operated solely. (2018-)
  • 🧑‍🤝‍🧑 Co-founded PopInSight (now part of Members Inc.) and developed user testing services. (2013-2017)
  • ⚙️ I automated software testing, and started a technical support team at beBit. (2008-2012)
  • 🗿 Further back in the day...
    • 👶 Born in Kanagawa (1985). During my childhood, I went back and forth between Japan and African countries.
    • ⛩️ Since I returned, I moved around the Kansai area a number of times, but my heart will always be at Kyoto.
    • 💼 The first service I was paid for, was the automation of submissions to search engines and ad spaces. (2000)
これまで
  • 🤝 個人事業として運営していたSlidePackなどを拡大するため、Qitar LLCを設立しました (2018-)
  • 🧑‍🤝‍🧑 PopInSight(今は株式会社メンバーズの傘下)を共同創業し、ユーザテストのサービスを開発していました (2013-2017)
  • ⚙️ beBitでソフトウェアテストの自動化や、テクニカルサポートチームの立ち上げを行いました (2008-2012)
  • 🗿 もっと昔は...
    • 👶 神奈川で生まれ(1985)、幼少期はアフリカ諸国に行ったり来たりしていました
    • ⛩️ 日本に戻ってからは関西を転々と…したものの、心の故郷は京都にあります
    • 💼 はじめて販売したサービスは検索エンジンや各種広告枠への投稿を自動化するものです (2000)
Others
  • 🤟 I'm a huge fan of Laravel, Tailwind CSS, Inertia.js
  • 💡 I often start developing services for myself or people close to me.
  • 🌱 Like how GitHub expanded the world, I would like to contribute to a future, in which the world is enriched by people supporting each other little by little.
  • 🎺 I play jazz trumpet.
ほか
  • 🤟 Laravel, Tailwind CSS, Inertia.jsを好んで使います
  • 💡 サービス開発は、自分自身や身近な人のためにはじめることが多いです
  • 🌱 GitHubで広がる世界のように、ビジネスでも、お互いに少しずつ支え合うことで豊かになっていく未来に貢献したいです
  • 🎺 ジャズトランペットを吹いています

laravel-dynamodb's People

Contributors

andreagroferreira avatar kitar avatar localpath avatar lucasgiovanny avatar madrussa avatar marvinosswald avatar mehedimi avatar negoziator avatar paulhenri-l avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

laravel-dynamodb's Issues

Support PHP 8.3 with Laravel 11

When I try install in Laravel 10 and PHP 8.1 it's ok!
but when I upgrade to Laravel 11 and PHP 8.3 I got this errors:

Problem 1
- kitar/laravel-dynamodb[v0.1.0, ..., v0.2.0] require php ^7.2 -> your php version (8.3.3) does not satisfy that requirement.
- kitar/laravel-dynamodb[v0.3.0, ..., v0.6.0] require illuminate/support ^6.0|^7.0|^8.0 -> found illuminate/support[v6.0.0, ..., v6.20.44, v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.27] but these were not loaded, likely because it conflicts with another require.
- kitar/laravel-dynamodb[v1.0.0, ..., v1.1.0] require illuminate/support ^6.0|^7.0|^8.0|^9.0 -> found illuminate/support[v6.0.0, ..., v6.20.44, v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.27, v9.0.0, ..., v9.52.16] but these were not loaded, likely because it conflicts with another require.
- kitar/laravel-dynamodb[v1.1.1, ..., v1.2.0] require illuminate/support ^6.0|^7.0|^8.0|^9.0|^10.0 -> found illuminate/support[v6.0.0, ..., v6.20.44, v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.27, v9.0.0, ..., v9.52.16, v10.0.0, ..., v10.48.2] but these were not loaded, likely because it conflicts with another require.
- Root composer.json requires kitar/laravel-dynamodb * -> satisfiable by kitar/laravel-dynamodb[v0.1.0, ..., v0.6.0, v1.0.0, ..., v1.2.0].

Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.

Hey Guys,

i am a newby at Laravel + DynomoDB.
I followed what is in the readme file. unfortunately I get the following error. What's the problem here?

Aws\DynamoDb\Exception\DynamoDbException

Error executing "Scan" on "dynamodb.eu-central-1.amazonaws.com"; AWS HTTP error: Client error: POST dynamodb.eu-central-1.amazonaws.com resulted in a 400 Bad Request response:
{"__type":"com.amazon.coral.service#InvalidSignatureException","message":"'Host' or ':authority' must be a 'SignedHeader (truncated...)
InvalidSignatureException (client): 'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization. - {"__type":"com.amazon.coral.service#InvalidSignatureException","message":"'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization."}

Does it support Migrations ?

Thank you very much for this great work. However, I wanted to know if does it support migrations. Because a downside of it is that I keep on getting error of cannot do x operation on non-existent table

Call to undefined method Kitar\Dynamodb\Query\Builder::getQuery()

Hi,

First thanks for the great work!

I am having an issue with the "missing" method getQuery() when attempting to fetch the records from a model via Laravel Nova.

I am using two databases, mysql and dynamdb. The system is writing to both. I cannot however read via Nova from the Dynamodb.

I get the above exception triggered from the BadMethodException on line 420 of Kitar\Dynamodb\Query\Builder.

From what I can understand of the Eloquent Query Builder all that getQuery() does is return the query object which be this stage is already defined.

Any assistance would be greatly appreciated.

Thanks

Filter model related records when using scan()

DynamoDB, by its nature, often stores multiple models in a single table.

This is not a problem when writing a query to narrow down like this,

App\Models\User::filter('sort', '=', 'profile')->scan();

but because we are scanning the model, it is more natural to just scan it.

App\Models\User::scan();

Global Scopes seems useful in this case, but since Scope is a feature of Eloquent Builder and we don't extend it (we extend Database Query Builder), we can't use Laravel's scope feature as it is.

AWS IAM role auth instead of IAM credentials

Hello, thanks for the library, works like a charm.
I have an ecs container with laravel.
Attached a role with dynamodb permissions I need, but looks like the library requires static AWS credentals and can't use IAM role.

Logs:

previous exception] [object] (GuzzleHttp\\Exception\\ClientException(code: 400): Client error: `POST https://dynamodb.eu-central-1.amazonaws.com` resulted in a `400 Bad Request` response:
{\"__type\":\"com.amazon.coral.service#UnrecognizedClientException\",\"message\":\"The security token included in the request i (truncated...)

File: config/database.php

        'dynamodb' => [
            'driver' => 'dynamodb',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
            'token' => env('AWS_SESSION_TOKEN', null),
            'endpoint' => env('DYNAMODB_ENDPOINT', null),
            'prefix' => env('DYNAMO_SUFFIX', ''),
        ],

aws environment variables

env | grep AWS
AWS_DEFAULT_REGION=eu-central-1
AWS_REGION=eu-central-1

aws cli command to get dynamodb access

 aws dynamodb scan --table-name  products
{
    "Items": [
        {
.....

Could you let me know, maybe I use it incorrectly. Didn't find anything about this issue in the documentation. Thanks

Support multiple expression types for wheres

QueryBuilder uses wheres attribute to handle the source for ConditionExpression KeyConditionExpression and FilterExpression like below.

DB::table('ProductCatalog')
    ->where('Id', 'attribute_not_exists')
    ->whereAsCondition()
    ->putItem(...);
$items = DB::table('Thread')
             ->where('ForumName', '=', 'Amazon DynamoDB')
             ->whereAsKeyCondition()
             ->query();
$items = DB::table('Thread')
             ->where('LastPostedBy', '=', 'User A')
             ->whereAsFilter()
             ->scan();

It can't be used for multiple expression types at the same time because it shares a single wheres attribute. Need to re-design this.

Add tests for nested wheres

Grammar uses original compileWheres() method to compile nested wheres, so QueryBuilder should work with nested wheres, but we don't have tests yet.

Deserializing model in event constructor fails for a queued event listener?

Hello. Ty for the great package. Using it I've come across a serialization issue when using queued event listeners. Seems like it's trying to connect on a null connection? Like it's reverting to the default database driver? Using the model created event and listening to that event with a queued event listener fails. I can toArray() or pass the DynamoDB partition keys to do a lookup but seems like laravel should be able to hydrate no matter the driver right?

Laravel 9.x
laravel-dynamodb 1.x

[2022-06-23 01:20:15] local.ERROR: Call to a member function prepare() on null {"exception":"[object] (Error(code: 0): Call to a member function prepare() on null at /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php:396)
[stacktrace]
#0 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php(735): Illuminate\\Database\\Connection->Illuminate\\Database\\{closure}('select * from \"...', Array)
#1 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php(702): Illuminate\\Database\\Connection->runQueryCallback('select * from \"...', Array, Object(Closure))
#2 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php(404): Illuminate\\Database\\Connection->run('select * from \"...', Array, Object(Closure))
#3 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2630): Illuminate\\Database\\Connection->select('select * from \"...', Array, false)
#4 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2618): Illuminate\\Database\\Query\\Builder->runSelect()
#5 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(3154): Illuminate\\Database\\Query\\Builder->Illuminate\\Database\\Query\\{closure}()
#6 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2619): Illuminate\\Database\\Query\\Builder->onceWithColumns(Array, Object(Closure))
#7 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(698): Illuminate\\Database\\Query\\Builder->get(Array)
#8 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(682): Illuminate\\Database\\Eloquent\\Builder->getModels(Array)
#9 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(74): Illuminate\\Database\\Eloquent\\Builder->get()
#10 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(56): App\\Events\\SystemEvents\\SystemEventCreated->restoreCollection(Object(Illuminate\\Contracts\\Database\\ModelIdentifier))
#11 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(126): App\\Events\\SystemEvents\\SystemEventCreated->getRestoredPropertyValue(Object(Illuminate\\Contracts\\Database\\ModelIdentifier))
#12 [internal function]: App\\Events\\SystemEvents\\SystemEventCreated->__unserialize(Array)
#13 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(96): unserialize('O:36:\"Illuminat...')
#14 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(257): Illuminate\\Queue\\CallQueuedHandler->getCommand(Array)
#15 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(213): Illuminate\\Queue\\CallQueuedHandler->failed(Array, Object(Error), 'c02f0cf2-5f3f-4...')
#16 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(192): Illuminate\\Queue\\Jobs\\Job->failed(Object(Error))
#17 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(581): Illuminate\\Queue\\Jobs\\Job->fail(Object(Error))
#18 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(527): Illuminate\\Queue\\Worker->failJob(Object(Illuminate\\Queue\\Jobs\\DatabaseJob), Object(Error))
#19 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(455): Illuminate\\Queue\\Worker->markJobAsFailedIfWillExceedMaxAttempts('database', Object(Illuminate\\Queue\\Jobs\\DatabaseJob), 1, Object(Error))
#20 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(432): Illuminate\\Queue\\Worker->handleJobException('database', Object(Illuminate\\Queue\\Jobs\\DatabaseJob), Object(Illuminate\\Queue\\WorkerOptions), Object(Error))
#21 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(378): Illuminate\\Queue\\Worker->process('database', Object(Illuminate\\Queue\\Jobs\\DatabaseJob), Object(Illuminate\\Queue\\WorkerOptions))
#22 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(329): Illuminate\\Queue\\Worker->runJob(Object(Illuminate\\Queue\\Jobs\\DatabaseJob), 'database', Object(Illuminate\\Queue\\WorkerOptions))
#23 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(130): Illuminate\\Queue\\Worker->runNextJob('database', 'unified-default...', Object(Illuminate\\Queue\\WorkerOptions))
#24 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(114): Illuminate\\Queue\\Console\\WorkCommand->runWorker('database', 'unified-default...')
#25 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Queue\\Console\\WorkCommand->handle()
#26 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Container/Util.php(41): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#27 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure(Object(Closure))
#28 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))
#29 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(651): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)
#30 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Container\\Container->call(Array)
#31 /var/www/unified-api/vendor/symfony/console/Command/Command.php(291): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#32 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#33 /var/www/unified-api/vendor/symfony/console/Application.php(998): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#34 /var/www/unified-api/vendor/symfony/console/Application.php(299): Symfony\\Component\\Console\\Application->doRunCommand(Object(Illuminate\\Queue\\Console\\WorkCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#35 /var/www/unified-api/vendor/symfony/console/Application.php(171): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#36 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Console/Application.php(102): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#37 /var/www/unified-api/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#38 /var/www/unified-api/artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#39 {main}
"} 

Enum support on query builder

Having a support enum as a value in the query builder would be nice, just like the model.

i.e.
Transaction::filter('status', '=', StatusEnum::SUCCESS)->scan();

Instead of doing this, stating the string:
Transaction::filter('status', '=', StatusEnum::SUCCESS->value)->scan();

InvalidArgumentException Unsupported driver [dynamodb].

I'm faced with this error:

Illuminate\Database\Connectors\ConnectionFactory::createConnection
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php:287

Am I missing something here?

image

Support whereIn

Add methods below to the QueryBuilder.

  • filterIn
  • conditionIn
  • keyConditionIn

Sorting does not work

Hi, I am trying to sort the data with sort key but it's not working.
Schema:

        $schema = [
            'AttributeDefinitions' => [
                [
                    'AttributeName' => 'id',
                    'AttributeType' => 'S',
                ],
                [
                    'AttributeName' => 'customer_id',
                    'AttributeType' => 'N',
                ],
                [
                    'AttributeName' => 'created_at',
                    'AttributeType' => 'S',
                ],
            ],
            'TableName' => $this->tableName,
            'KeySchema' => [
                [
                    'AttributeName' => 'id',
                    'KeyType' => 'HASH',
                ],
                [
                    'AttributeName' => 'created_at',
                    'KeyType' => 'RANGE',
                ],
            ],
            'StreamSpecification' => [
                'StreamEnabled' => true,
                'StreamViewType' => 'NEW_AND_OLD_IMAGES',
            ],
            'GlobalSecondaryIndexes' => [
                [
                    'IndexName' => 'gsi_0',
                    'Projection' => [
                        'ProjectionType' => 'ALL',
                    ],
                    'KeySchema' => [
                        [
                            'AttributeName' => 'customer_id',
                            'KeyType' => 'HASH',
                        ],
                        [
                            'AttributeName' => 'created_at',
                            'KeyType' => 'RANGE',
                        ],
                    ],
                    'BillingMode' => 'PAY_PER_REQUEST',
                ],
            ],
            'BillingMode' => 'PAY_PER_REQUEST',
        ];

Model:

class AuditLog extends Model
{
    protected $connection= 'dynamodb';
    protected $table = "";
    protected $primaryKey = 'id';
    protected $sortKey = 'created_at';
    protected $fillable = ["id", "log_text", "customer_id", "created_at"];
}

Controller:

$data = AuditLog::limit(5)->scanIndexForward(false)->scan();
$response = [
    "success" => true,
    "data" => $data, 
];
return response($response, 201);

Integration with laravel-activitylog

Hi everybody. I am trying to implement laravel-activitylog contracts with your library. I have a problem calling $this->MorphTo() because dynamodb does not support connections. How can I fix or replace this logic?

where -> delete

Is there support to delete more than one record at a time? You can scan the dataset using the where, but not delete?

Support Transaction

Since DynamoDB uses HTTP connection model, it's important to keep requests count as few as possible. For example, if we try to maintain "likes" count, we would do:

  1. Add like if the user didn't liked yet.
  2. If added, increment the counter.

We can execute them in a single request with Transaction.

Filter on keys in map attribute type

Hi,

First, thanks for creating this great package :-)

Is there any way to filter on keys in the map attribute type?

Example:
->filter('person.name', 'John')

I'm still new to DynamoDb and I'm sorry if I'm missing something obvious.

Actually, I did a temporary hack to solve it. Seems to work for my use case, but not very well tested.

// Builder.php

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
    // Convert column and value to ExpressionAttributes.
    if (! $column instanceof Closure) {
        // The column has nested keys
        if (Str::contains($column, '.')) {
            $column = Str::of($column)
                ->explode('.')
                ->map(fn ($attribute) => $this->expression_attributes->addName($attribute))
                ->implode('.');
        } else {
            $column = $this->expression_attributes->addName($column);
        }

        if ($value !== null) {
            $value = $this->expression_attributes->addValue($value);
        }
    }
   ...

Support orWhere

Add methods below to the QueryBuilder.

  • orFilter
  • orCondition
  • orKeyCondition

Support for Factories

Should the Factories work? I get this error:

Call to undefined method Illuminate\Database\Query\Builder::usingModel()

The entry ends up in the local dynamodb but an error is thrown.

Model


 use Kitar\Dynamodb\Model\Model as DynamoModel;

 class ExampleDynamoDbModel extends DynamoModel
{
    use HasFactory;

   protected $connection = 'dynamodb';

    protected $table = 'example_table';
    protected $primaryKey = 'my_primary_key';
    protected $sortKey = 'my_sort_key';
    protected $fillable = [
        'my_primary_key',
        'my_sort_key',
    ];
}
create table '{
  "TableDescription": {
    "AttributeDefinitions": [
      {
        "AttributeName": "my_primary_key","AttributeType": "N"
      },{
        "AttributeName": "my_sort_key","AttributeType": "N"
      }
    ],"TableName": "local_example_table",
    "KeySchema": [
      {
        "AttributeName": "my_primary_key","KeyType": "HASH"
      },{
        "AttributeName": "my_sort_key","KeyType": "SORT"
      }
    ],
    "ProvisionedThroughput": {
      "ReadCapacityUnits": 1,"WriteCapacityUnits": 1
    },
    "TableClassSummary": {
      "TableClass": "STANDARD"
    }
  }
}';

Factory

<?php

namespace Database\Factories\DynamoDb;

use Illuminate\Database\Eloquent\Factories\Factory;

class ExampleDynamoDbModelFactory extends Factory
{

    public function definition(): array
    {
        return [
            'my_primary_key' => $this->faker->randomNumber(),
            'my_sort_key' => $this->faker->randomNumber(),
        ];
    }
}

Seeder

<?php

namespace Database\Seeders;

use App\Models\DynamoDb\ExampleDynamoDbModel;
use Illuminate\Database\Seeder;

class ExampleDynamoDbModelSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // This works
        $model = new ExampleDynamoDbModel();
        $model->my_primary_key = rand();
        $model->my_sort_key = rand();
        $model->save();

        // This throws the error
        $data = ExampleDynamoDbModel::factory()->count(1)->create();
    }
}

Error Message

 sail debug db:seed --class "Database\Seeders\ExampleDynamoDbModelSeeder"

   INFO  Seeding database.  

[2024-02-02 00:52:26] local.ERROR: Call to undefined method Illuminate\Database\Query\Builder::usingModel() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method Illuminate\\Database\\Query\\Builder::usingModel() at /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:67)
[stacktrace]
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(3967): Illuminate\\Database\\Query\\Builder::throwBadMethodCallException()
#1 /var/www/html/vendor/kitar/laravel-dynamodb/src/Kitar/Dynamodb/Model/Model.php(97): Illuminate\\Database\\Query\\Builder->__call()
#2 /var/www/html/vendor/kitar/laravel-dynamodb/src/Kitar/Dynamodb/Model/Model.php(154): Kitar\\Dynamodb\\Model\\Model->newQuery()
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php(338): Kitar\\Dynamodb\\Model\\Model->save()
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php(240): Illuminate\\Database\\Eloquent\\Factories\\Factory->Illuminate\\Database\\Eloquent\\Factories\\{closure}()
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php(333): Illuminate\\Support\\Collection->each()
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php(291): Illuminate\\Database\\Eloquent\\Factories\\Factory->store()

#7 /var/www/html/database/seeders/ExampleDynamoDbModelSeeder.php(21): Illuminate\\Database\\Eloquent\\Factories\\Factory->create()

#8 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Database\\Seeders\\ExampleDynamoDbModelSeeder->run()
#9 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Util.php(41): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#10 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure()
#11 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\\Container\\BoundMethod::callBoundMethod()
#12 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(662): Illuminate\\Container\\BoundMethod::call()
#13 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Seeder.php(184): Illuminate\\Container\\Container->call()
#14 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Seeder.php(193): Illuminate\\Database\\Seeder->Illuminate\\Database\\{closure}()
#15 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(70): Illuminate\\Database\\Seeder->__invoke()
#16 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php(155): Illuminate\\Database\\Console\\Seeds\\SeedCommand->Illuminate\\Database\\Console\\Seeds\\{closure}()
#17 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(69): Illuminate\\Database\\Eloquent\\Model::unguarded()
#18 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Database\\Console\\Seeds\\SeedCommand->handle()
#19 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Util.php(41): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#20 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure()
#21 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\\Container\\BoundMethod::callBoundMethod()
#22 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(662): Illuminate\\Container\\BoundMethod::call()
#23 /var/www/html/vendor/laravel/framework/src/Illuminate/Console/Command.php(211): Illuminate\\Container\\Container->call()
#24 /var/www/html/vendor/symfony/console/Command/Command.php(326): Illuminate\\Console\\Command->execute()
#25 /var/www/html/vendor/laravel/framework/src/Illuminate/Console/Command.php(180): Symfony\\Component\\Console\\Command\\Command->run()
#26 /var/www/html/vendor/symfony/console/Application.php(1096): Illuminate\\Console\\Command->run()
#27 /var/www/html/vendor/symfony/console/Application.php(324): Symfony\\Component\\Console\\Application->doRunCommand()
#28 /var/www/html/vendor/symfony/console/Application.php(175): Symfony\\Component\\Console\\Application->doRun()
#29 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(201): Symfony\\Component\\Console\\Application->run()
#30 /var/www/html/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle()
#31 {main}
"} 

   BadMethodCallException 

  Call to undefined method Illuminate\Database\Query\Builder::usingModel()

  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:67
     63▕      * @throws \BadMethodCallException
     64▕      */
     65▕     protected static function throwBadMethodCallException($method)
     66▕     {
  ➜  67▕         throw new BadMethodCallException(sprintf(
     68▕             'Call to undefined method %s::%s()', static::class, $method
     69▕         ));
     70▕     }
     71▕ }

  i   Bad Method Call: Did you mean Illuminate\Database\Query\Builder::useIndex() ? 

      +7 vendor frames 

  8   database/seeders/ExampleDynamoDbModelSeeder.php:21
      Illuminate\Database\Eloquent\Factories\Factory::create()
      +22 vendor frames 

  31  artisan:35
      Illuminate\Foundation\Console\Kernel::handle()
``

Endpoint config issue when using with Docker

I am using docker and my endpoint is:
DYNAMODB_ENDPOINT=dynamodb:8000

This causes failure:
image

Suggested edit (ie let developer specify the exact endpoint they want to use, dont force https or even http onto it):
image

Add tests for Grammar::compile[function]Condition()

QueryBuilder can handle functions in where clause, but we don't have tests yet.

  • compileAttributeExistsCondition()
  • compileAttributeNotExistsCondition()
  • compileAttributeTypeCondition()
  • compileBeginsWithCondition()
  • compileContainsCondition()
  • compileSizeCondition()

Write tests and make sure they works well.

Config parameter names in README incorrect

In the Readme of this repo it states to use key and secret when creating a connection

'connections' => [

    'dynamodb' => [
        'driver' => 'dynamodb',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
        'token' => env('AWS_SESSION_TOKEN', null),
        'endpoint' => env('DYNAMODB_ENDPOINT', null),
        'prefix' => '', // table prefix
    ],

    ...

],

however in Connection.php the sdk is initiated as:

$sdk = new AwsSdk([
            'region' => $config['region'] ?? 'us-east-1',
            'version' => $config['version'] ?? 'latest',
            'credentials' => [
                'key' => $config['access_key'] ?? '',
                'secret' => $config['secret_key'] ?? ''
            ]
        ]);

where the key is expected to come from a config parameter called access_key and the secret from a config parameter named secret_key.

didn't get all the data

Table json

{
  "AttributeDefinitions": [
    {
      "AttributeName": "ID",
      "AttributeType": "S"
    },
    {
      "AttributeName": "CreatedAt",
      "AttributeType": "S"
    }
  ],
  "TableName": "Sanction",
  "KeySchema": [
    {
      "AttributeName": "ID",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "CreatedAt",
      "KeyType": "RANGE"
    }
  ],
  "TableStatus": "ACTIVE",
  "CreationDateTime": "2023-09-20T09:22:24.651Z",
  "ProvisionedThroughput": {
    "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z",
    "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z",
    "NumberOfDecreasesToday": 0,
    "ReadCapacityUnits": 5,
    "WriteCapacityUnits": 5
  },
  "TableSizeBytes": 33784353,
  "ItemCount": 24403,
  "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/UKSanctionList"
}

Model Sanction

class Sanction extends Model
{
    protected $table = 'UKSanctionList';
    protected $primaryKey = 'UniqueID';
    // Name of the sort key (optional)
    protected $sortKey = 'CreatedAt';
    protected $sortKeyDefault = 'CreatedAt';
}

I have more than 40k data in the Sanction table, but I only get 755 data
Is it limited? , so I can't filter the data I want

thank you before

Support whereBetween

Add methods below to the QueryBuilder.

  • filterBetween
  • conditionBetween
  • keyConditionBetween

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.