Explore all Migration open source software, libraries, packages, source code, cloud functions and APIs.

Explore Related Topics

Popular New Releases in Migration

gh-ost

GA release v1.1.4

migrations

3.5.0

phinx

0.12.10

goose

v3.5.3

mara-pipelines

Version 3.1.1

Popular Libraries in Migration

gh-ost

by github doticongodoticon

star image 9676 doticonMIT

GitHub's Online Schema Migrations for MySQL

pentaho-kettle

by pentaho doticonjavadoticon

star image 5719 doticonApache-2.0

Pentaho Data Integration ( ETL ) a.k.a Kettle

ts-migrate

by airbnb doticontypescriptdoticon

star image 4329 doticonMIT

A tool to help migrate JavaScript code quickly and conveniently to TypeScript

migrations

by doctrine doticonphpdoticon

star image 4309 doticonMIT

Doctrine Database Migrations Library

phinx

by cakephp doticonphpdoticon

star image 4266 doticonMIT

PHP Database Migrations for Everyone

migrations-generator

by Xethron doticonphpdoticon

star image 3229 doticonMIT

Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

rudder-server

by rudderlabs doticongodoticon

star image 3067 doticonAGPL-3.0

Privacy and Security focused Segment-alternative, in Golang and React

goose

by pressly doticongodoticon

star image 2481 doticonNOASSERTION

A database migration tool. Supports SQL migrations and Go functions.

migra

by djrobstep doticonpythondoticon

star image 2441 doticonUnlicense

Like diff but for PostgreSQL schemas

Trending New libraries in Migration

laravel-migrations-generator

by kitloong doticonphpdoticon

star image 924 doticonMIT

Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

deno-nessie

by halvardssm doticontypescriptdoticon

star image 471 doticonMIT

A modular Deno library for PostgreSQL, MySQL, MariaDB and SQLite migrations

aerich

by tortoise doticonpythondoticon

star image 450 doticonApache-2.0

A database migrations tool for TortoiseORM, ready to production.

django-upgrade

by adamchainz doticonpythondoticon

star image 313 doticonMIT

Automatically upgrade your Django projects.

laravel-migration-generator

by bennett-treptow doticonphpdoticon

star image 287 doticonMIT

Generate migrations from existing database structures

almalinux-deploy

by AlmaLinux doticonshelldoticon

star image 145 doticonGPL-3.0

EL to AlmaLinux migration tool.

etl

by flow-php doticonphpdoticon

star image 124 doticonMIT

PHP - ETL (Extract Transform Load) data processing library

ETL-pipeline

by renatootescu doticonpythondoticon

star image 105 doticonMIT

Educational project on how to build an ETL (Extract, Transform, Load) data pipeline, orchestrated with Airflow.

data-story

by ajthinking doticoncssdoticon

star image 95 doticon

A visual process builder

Top Authors in Migration

1

fusionjs

15 Libraries

star icon840

2

blockchain-etl

6 Libraries

star icon43

3

thehyve

4 Libraries

star icon22

4

deprecated-packages

4 Libraries

star icon38

5

contributte

4 Libraries

star icon70

6

scriptella

3 Libraries

star icon115

7

m-lab

3 Libraries

star icon25

8

aa900031

3 Libraries

star icon11

9

OHDSI

3 Libraries

star icon55

10

microsoft

3 Libraries

star icon134

1

15 Libraries

star icon840

2

6 Libraries

star icon43

3

4 Libraries

star icon22

4

4 Libraries

star icon38

5

4 Libraries

star icon70

6

3 Libraries

star icon115

7

3 Libraries

star icon25

8

3 Libraries

star icon11

9

3 Libraries

star icon55

10

3 Libraries

star icon134

Trending Kits in Migration

Libraries for Mongoose schema migration and versioning are tools. They help developers manage changes to their database structure. They keep track of different versions of their data schema. This is all for those using MongoDB with Mongoose in JavaScript apps. 


These libraries make it easy to update database schemas. They provide simple commands and interfaces. 

  • They allow developers to write migration scripts in JavaScript. This makes it flexible and easy to make changes. 
  • Additionally, they often support transactions. These ensure that database changes keep data integrity during the migration. 
  • These libraries have features like versioning support. They let developers manage many versions of their data schema well. 
  • This ensures that existing data stays compatible. It stays compatible even as the schema changes over time. 
  • They integrate with Mongoose. They make it easier to manage schema changes and migrate data. 

In general, tools for Mongoose schema migration and versioning make it easier. They make it easier to update database schemas. They also maintain data integrity and manage schema versions. This makes database management tasks faster and less error-prone for developers. 

migrate-mongo: 

  • Although designed for MongoDB, you can adapt it for other databases. 
  • Provides a straightforward command-line interface for managing migrations. 
  • You can write migration scripts in JavaScript, which allows flexibility. 
  • Supports transactions to maintain data integrity during migrations. 

mongoose-fixtures: 

  • Facilitates seeding initial data into MongoDB collections. 
  • Allows defining fixtures in JSON format for easy configuration. 
  • Enables defining dependencies between fixtures for proper seeding order. 
  • integrates with Mongoose for data manipulation and validation. 


mongoose-version: 

  • Offers versioning support for Mongoose schemas. 
  • migrates documents between schema versions during read/write operations. 
  • Ensures backward compatibility by supporting many schema versions. 
  • Integrate with Mongoose for schema management and data migration. 

umzug: 

  • Supports many database types, not MongoDB. 
  • Allows customization of migration paths and behavior. 
  • Offers a programmatic API for integrating migration tasks into your codebase. 
  • Depending on the database, it may support transactions for migrations. 

mongeez: 

  • Utilizes XML files for defining migration scripts, providing a structured approach. 
  • Supports incremental changes to the database schema over time. 
  • Tracks the execution of migration scripts to avoid reapplying them. 
  • Designed for MongoDB, ensuring compatibility. 

custom-scripts: 

  • Allows complete customization of migration scripts to fit specific requirements. 
  • You can integrate it into existing code bases or deployment pipelines. 
  • Provides full control over the migration process and its effects. 
  • Enables managing dependencies between migration scripts. 

event-sourcing-examples: 

  • Provides examples and implementations of event sourcing patterns. 
  • Offers practical examples to understand event sourcing in different scenarios. 
  • Acts as a learning resource for developers interested in implementing event sourcing. 
  • Provides a foundation for building custom event-sourcing implementations. 

FAQ 

1.How do I handle database migrations? This is when migrating from MongoDB to another database using migrate-mongo. 

Migrate-mongo developers designed it for MongoDB. But you could adapt it for different databases. You do this by changing migration scripts and configurations to fit the new database. 

 

2.Can I run specific migration scripts with migrate-mongo? 

Yes, migrate-mongo lets you run some migration scripts. You can run them up to a certain point. This flexibility helps in managing database changes. 

 

3.Do mongoose-fixtures support data validation during seeding? 

Yes, mongoose-fixtures works with Mongoose. It does data manipulation and validation. This ensures that seeded data follows defined schemas. 

 

 4.How does mongooseversion ensure backward compatibility when managing many schema versions? 

Mongoose-version supports many schema versions at once. It migrates documents between versions during read/write operations. This keeps backward compatibility. 

 

5.Can umzug work with databases other than MongoDB? 

Yes, umzug supports many database types. It's not MongoDB. This makes umzug adaptable to different databases. 

 

6.Does Mongeez provide any safeguards to prevent reapplying migration scripts? 

Yes, Montez tracks the migration script's execution. It applies to them only once. It avoids unintended side effects during updates. 

 

7.How do event-sourcing-examples help developers understand event-sourcing patterns? 

Event-sourcing examples offer practical examples and implementations of event sourcing. It provides hands-on learning for developers. They are interested in integrating event-driven architectures into their applications. 

Trending Discussions on Migration

Android : Could not GET/Find get repos from bintray.com

Call to undefined method App\Models\Category::factory() laravel

What exactly are the rules for configuring postcss.config.js (mainly with tailwndcss)?

How to use scoped APIs with (GSI) Google Identity Services

Attempting to register a user on my devise app causes undefined method `user_url' for #<Devise::RegistrationsController:0x0000000000d9d0>

Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException

Lambda expressions and anonymous classes don't work when loaded as hidden classes

"Cannot read properties of undefined (reading 'pathname')" when testing pages in the v6 React Router

pymongo [SSL: CERTIFICATE_VERIFY_FAILED]: certificate has expired on Mongo Atlas

How to log production database changes made via the Django shell

QUESTION

Android : Could not GET/Find get repos from bintray.com

Asked 2022-Apr-01 at 19:21

Trying to run old project with following config in build.gradle (root) file.

1// Top-level build file where you can add configuration options common to all sub-projects/modules.
2
3buildscript {
4    
5    repositories {
6        google()
7//        jcenter() //deprecated
8        mavenCentral()
9
10    }
11    dependencies {
12        classpath 'com.android.tools.build:gradle:3.3.1'
13        classpath 'me.tatarka:gradle-retrolambda:3.6.1'
14        classpath 'com.google.gms:google-services:4.2.0'
15        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
16//        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' //getting error because of this error so commented
17
18        // NOTE: Do not place your application dependencies here; they belong
19        // in the individual module build.gradle files
20    }
21}
22
23allprojects {
24    repositories {
25        google()
26//        maven { url "http://dl.bintray.com/populov/maven" } //getting error because of this error so commented 
27        maven {url "https://maven.google.com"}
28        maven { url 'https://jitpack.io' }
29        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
30        mavenCentral()
31        //        jcenter() //deprecated
32
33    }
34}
35
36task clean(type: Delete) {
37    delete rootProject.buildDir
38}
39

Got Error:

1: Could not GET 'http://dl.bintray.com/populov/maven/com/google/maps/android/android-maps-utils/maven-metadata.xml'

Received status code 502 from server: Bad Gateway

2:Could not resolve com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3

I got it, Since jcenter() is shutdown, i need to use mavenCentral() and find replacement for outdated packages. i tried to replace with mavenCentral(). and try to find alternative but could not.. tried with commenting, those error giving repos, but still can not fetch my required dependencies.

Referred to Android Studio: Gradle sync failed: Could not HEAD '...'. Received status code 502 from server: Bad Gateway

Difference among mavenCentral(), jCenter() and mavenLocal()?

Bintray is now sunsetted

Jcenter 502 bad gateway after gradle refresh

Commented Following Repo In (build.gradle):

1// Top-level build file where you can add configuration options common to all sub-projects/modules.
2
3buildscript {
4    
5    repositories {
6        google()
7//        jcenter() //deprecated
8        mavenCentral()
9
10    }
11    dependencies {
12        classpath 'com.android.tools.build:gradle:3.3.1'
13        classpath 'me.tatarka:gradle-retrolambda:3.6.1'
14        classpath 'com.google.gms:google-services:4.2.0'
15        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
16//        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' //getting error because of this error so commented
17
18        // NOTE: Do not place your application dependencies here; they belong
19        // in the individual module build.gradle files
20    }
21}
22
23allprojects {
24    repositories {
25        google()
26//        maven { url "http://dl.bintray.com/populov/maven" } //getting error because of this error so commented 
27        maven {url "https://maven.google.com"}
28        maven { url 'https://jitpack.io' }
29        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
30        mavenCentral()
31        //        jcenter() //deprecated
32
33    }
34}
35
36task clean(type: Delete) {
37    delete rootProject.buildDir
38}
39 repositories: // maven { url "http://dl.bintray.com/populov/maven" }
40 dependencies: // classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
41

Error: After I commented above libraries , I got following error :

erro: screenshot

Any suggestion on migration or package replacement or quick fix would be great help.. Thank you.

ANSWER

Answered 2022-Apr-01 at 19:21

if you go to the missing library's Github page, you see that it was available only through jcenter, and since jcenter is down, you need to clone the library and build it yourself and put it on the classpath.

Source https://stackoverflow.com/questions/71583997

QUESTION

Call to undefined method App\Models\Category::factory() laravel

Asked 2022-Mar-31 at 13:28

I have the error stated above, and here is the copy log

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27

Here is the databaseseeder.php class since the error is there:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76

There is the error line:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77

Here we got the category class:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93

Here we got the category factory:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123

Here is the category migration:

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123<?php
124
125use App\Models\Product;
126use Illuminate\Database\Migrations\Migration;
127use Illuminate\Database\Schema\Blueprint;
128use Illuminate\Support\Facades\Schema;
129
130class CreateCategoriesTable extends Migration
131{
132    /**
133     * Run the migrations.
134     *
135     * @return void
136     */
137    public function up()
138    {
139        Schema::create('categories', function (Blueprint $table) {
140            $table->increments('id');
141            $table->string('name');
142            $table->string('description', 1000);
143            $table->integer('quantity')->unsigned();
144            $table->string('status')->default(Product::PRODUCTO_NO_DISPONIBLE);
145            $table->string('image');
146            $table->integer('seller_id')->unsigned();
147            $table->timestamps();
148
149            $table->foreign('seller_id')->references('id')->on('users');
150        });
151    }
152
153    /**
154     * Reverse the migrations.
155     *
156     * @return void
157     */
158    public function down()
159    {
160        Schema::dropIfExists('categories');
161    }
162}
163

I am posting all you need since I am new to this and I cannot find the problem.

ANSWER

Answered 2021-Aug-01 at 00:51

You need to use the factory trait for the model to have the factory() method available.

1php artisan db:seed
2
3   BadMethodCallException
4
5  Call to undefined method App\Models\Category::factory()
6
7  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
8     46▕      * @throws \BadMethodCallException
9     47▕      */
10     48▕     protected static function throwBadMethodCallException($method)
11     49▕     {
12  ➜  50▕         throw new BadMethodCallException(sprintf(
13     51▕             'Call to undefined method %s::%s()', static::class, $method
14     52▕         ));
15     53▕     }
16     54▕ }
17
18  • Bad Method Call: Did you mean App\Models\Category::toArray() ?
19
20      +3 vendor frames
21  4   database/seeders/DatabaseSeeder.php:38
22      Illuminate\Database\Eloquent\Model::__callStatic()
23
24      +22 vendor frames
25  27  artisan:37
26      Illuminate\Foundation\Console\Kernel::handle()
27<?php
28
29namespace Database\Seeders;
30
31use App\Models\Category;
32use App\Models\Product;
33use App\Models\Transaction;
34use App\Models\User;
35use Illuminate\Database\Seeder;
36
37use Illuminate\Support\Facades\DB;
38
39class DatabaseSeeder extends Seeder
40{
41    /**
42     * Seed the application's database.
43     *
44     * @return void
45     */
46    public function run()
47    {
48        // \App\Models\User::factory(10)->create();
49
50        DB::statement('SET FOREIGN_KEY_CHECKS=0');
51
52        User::truncate();
53        Category::truncate();
54        Product::truncate();
55        Transaction::truncate();
56        DB::table('category_product')->truncate();
57
58        $cantidadUsuarios = 200;
59        $cantidadCategories = 30;
60        $cantidadProductos = 1000;
61        $cantidadTransacciones = 1000;
62
63        \App\Models\User::factory()->count($cantidadUsuarios)->create();
64        \App\Models\Category::factory()->count($cantidadUsuarios)->create();
65
66        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
67            function ($producto) {
68                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
69                $producto->categories()->attach($categorias);
70            }
71        );
72
73        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
74    }
75}
76\App\Models\Category::factory()->count($cantidadUsuarios)->create();
77<?php
78
79namespace App\Models;
80
81use Illuminate\Database\Eloquent\Factories\HasFactory;
82use Illuminate\Database\Eloquent\Model;
83
84class Category extends Model
85{
86    public $table = "categories";
87
88    protected $fillable = [
89        'name',
90        'description',
91    ];
92}
93<?php
94
95namespace Database\Factories;
96
97use App\Models\Category;
98use Illuminate\Database\Eloquent\Factories\Factory;
99
100class CategoryFactory extends Factory
101{
102    /**
103     * The name of the factory's corresponding model.
104     *
105     * @var string
106     */
107    protected $model = Category::class;
108
109    /**
110     * Define the model's default state.
111     *
112     * @return array
113     */
114    public function definition()
115    {
116        return [
117            //
118             'name' => $this->faker->word,
119            'description' => $this->faker->paragraph(1),
120        ];
121    }
122}
123<?php
124
125use App\Models\Product;
126use Illuminate\Database\Migrations\Migration;
127use Illuminate\Database\Schema\Blueprint;
128use Illuminate\Support\Facades\Schema;
129
130class CreateCategoriesTable extends Migration
131{
132    /**
133     * Run the migrations.
134     *
135     * @return void
136     */
137    public function up()
138    {
139        Schema::create('categories', function (Blueprint $table) {
140            $table->increments('id');
141            $table->string('name');
142            $table->string('description', 1000);
143            $table->integer('quantity')->unsigned();
144            $table->string('status')->default(Product::PRODUCTO_NO_DISPONIBLE);
145            $table->string('image');
146            $table->integer('seller_id')->unsigned();
147            $table->timestamps();
148
149            $table->foreign('seller_id')->references('id')->on('users');
150        });
151    }
152
153    /**
154     * Reverse the migrations.
155     *
156     * @return void
157     */
158    public function down()
159    {
160        Schema::dropIfExists('categories');
161    }
162}
163class Category extends Model
164{
165   use HasFactory;
166
167   ...
168}
169

Source https://stackoverflow.com/questions/68606726

QUESTION

What exactly are the rules for configuring postcss.config.js (mainly with tailwndcss)?

Asked 2022-Mar-29 at 11:40

The number of variants that exist to showcase how postcss.config.js has to be configured is extremely confusing. There are examples (like the one at the tailwindcss documentation) that use this:

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8

then there are those which require the libraries:

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18

Others require external libs before they configure module.exports:

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30

and again some more that are necessary, when a configuration file that is not named according to the defaults has to be incorporated.

Today I get this error, when running yarn dev with a postcss.config.js as show in Example 2:

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35

When I remove the line with "tailwindcss", the same thing happens for "postcss-preset-env":

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40

When I then switch to a setup as shown in example 1, I get this error:

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43

I do use postcss 8.3.9!

This all happens in a project that was setup with vue-cli as a Vue2 project.

Which witch craft do I have to apply to make this setup work?

ANSWER

Answered 2021-Oct-26 at 14:58

In your terminal run the below command to install tailwind css and its dependencies via npm.

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44

It is possible to get the error message that you mentioned when you try to run the project

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45

Run the following code to uninstall previous installation and fix the error

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45npm uninstall tailwindcss postcss autoprefixer 
46npm install tailwindcss@npm:@tailwindcss/postcss7-compat@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
47

Next, you need to generate both Tailwind and PostCSS config files

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45npm uninstall tailwindcss postcss autoprefixer 
46npm install tailwindcss@npm:@tailwindcss/postcss7-compat@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
47npx tailwindcss init -p
48

Your config files should look like this

postcss.config file

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45npm uninstall tailwindcss postcss autoprefixer 
46npm install tailwindcss@npm:@tailwindcss/postcss7-compat@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
47npx tailwindcss init -p
48module.exports = {
49  plugins: {
50    tailwindcss: {},
51    autoprefixer: {},
52  },
53};
54

tailwindcss.config file

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45npm uninstall tailwindcss postcss autoprefixer 
46npm install tailwindcss@npm:@tailwindcss/postcss7-compat@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
47npx tailwindcss init -p
48module.exports = {
49  plugins: {
50    tailwindcss: {},
51    autoprefixer: {},
52  },
53};
54module.exports = {
55  future: {
56    // removeDeprecatedGapUtilities: true,
57    // purgeLayersByDefault: true,
58  },
59  purge: [],
60  theme: {
61    extend: {},
62  },
63  variants: {},
64  plugins: [],
65};
66

Finally, open up your main.js file and import the tailwind.css file containing the tailwind directives i.e

1// Example 1:
2module.exports = {
3  plugins: {
4    tailwindcss: {},
5    autoprefixer: {},
6  },
7}
8// Example 2:
9module.exports = {
10  plugins: {
11    require('tailwindcss'),
12    require('postcss-preset-env')({
13      stage: 0,
14      'nesting-rules': true
15    })
16  },
17}
18// Example 3:
19
20const tailwindcss = require('tailwindcss');
21const postcssPresetEnv = require('postcss-preset-env');
22
23
24module.exports = {
25  plugins: {
26    tailwindcss,
27    postcssPresetEnv
28  },
29}
30Syntax Error: /[path]/_pod-test/postcss.config.js:3
31    require('tailwindcss'),
32             ^^^^^^^^^^^
33
34SyntaxError: Unexpected string
35Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
36    require('postcss-preset-env')({
37            ^^^^^^^^^^^^^^^^^^^^
38
39SyntaxError: Unexpected string
40Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
41Migration guide for end-users:
42https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
43npm install tailwindcss postcss autoprefixer
44Error: PostCSS plugin tailwindcss requires PostCSS 8.
45npm uninstall tailwindcss postcss autoprefixer 
46npm install tailwindcss@npm:@tailwindcss/postcss7-compat@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
47npx tailwindcss init -p
48module.exports = {
49  plugins: {
50    tailwindcss: {},
51    autoprefixer: {},
52  },
53};
54module.exports = {
55  future: {
56    // removeDeprecatedGapUtilities: true,
57    // purgeLayersByDefault: true,
58  },
59  purge: [],
60  theme: {
61    extend: {},
62  },
63  variants: {},
64  plugins: [],
65};
66import './css/tailwind.css'
67

Source https://stackoverflow.com/questions/69725289

QUESTION

How to use scoped APIs with (GSI) Google Identity Services

Asked 2022-Mar-17 at 00:31

Google recently sent me an email with the following:

One or more of your web applications uses the legacy Google Sign-In JavaScript library. Please migrate your project(s) to the new Google Identity Services SDK before March 31, 2023

The project in question uses the Google Drive API alongside the now legacy authentication client.

The table on the migration page (https://developers.google.com/identity/gsi/web/guides/migration) says:

Old New Notes
JavaScript libraries
apis.google.com/js/platform.js accounts.google.com/gsi/client Replace old with new.
apis.google.com/js/api.js accounts.google.com/gsi/client Replace old with new.

I was currently using gapi on the front-end to perform authorization which is loaded from apis.google.com/js/api.js. According to the table I would need to replace it with the new library.

I've tried the following to authenticate and authorize in the same manner that I used to do with gapi:

1window.google.accounts.id.initialize({
2  client_id: GOOGLE_CLIENT_ID,
3  callback: console.log,
4  scope: "https://www.googleapis.com/auth/drive.file",
5  discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
6});
7
8window.google.accounts.id.renderButton(ref.current, {
9  size: "medium",
10  type: "standard",
11});
12
13

However, when I try to authenticate with the Google Sign In button, the scope field is not respected and it does not ask the user to authorize the requested scopes. It also doesn't return any form of access token in the Credential Response in the callback.

I'm not sure how else to authorize using the new library.

ANSWER

Answered 2021-Aug-26 at 19:19

In the new Gooogle Identity Services, the authentication moment and the authorization moment are separated. This means, GIS provides different APIs for websites to call on these two different moments. You cannot combine them together in one API call (and UX flow) any more.

In the authenction moment, users just sign in or sign up into your website (by leveraging the information shared by Google). The only decision users need to make is whether they want to sign in (or sign-up). No authorization-related decison need to make at this point.

In the authentication moment, users will see consistent One Tap or button UX across all websites (since the same scopes are requested implicitly). Consistence leads to more smoothly UX, which may further lead to more usage. With the consitent and optimized authentication UX (across all websites), users will have a better experience with federated sign-in.

After users sign-in, when you really want to load some data from a Google data service, you can call GIS authorization API to trigger an UX flow to allow end users to grant the permission. That's the authorization moment.

Currently (August 2021), only authentication API has been published. If your website only cares about authentication, you can migrate to GIS now. If you also need the authorization API, you have to wait for further notice.

Source https://stackoverflow.com/questions/68815693

QUESTION

Attempting to register a user on my devise app causes undefined method `user_url' for #<Devise::RegistrationsController:0x0000000000d9d0>

Asked 2022-Mar-04 at 13:29

I am getting this error when I try to sign up a user. After this error, I'm still able to sign in with the user it would've created, but it always shows me this upon registration. Please let me know if there's other information you need. Been stumped on this for a few days.

enter image description here

Here is the exception causes: enter image description here

Here is the callback for the error:

1actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:231:in `public_send' 
2actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:231:in `polymorphic_method' 
3actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:116:in `polymorphic_url' 
4actionpack (7.0.0) lib/action_dispatch/routing/url_for.rb:187:in `full_url_for' 
5actionpack (7.0.0) lib/action_dispatch/routing/url_for.rb:170:in `url_for' 
6actionpack (7.0.0) lib/action_controller/metal/redirecting.rb:144:in `_compute_redirect_to_location' 
7actionpack (7.0.0) lib/action_controller/metal/redirecting.rb:89:in `redirect_to' 
8actionpack (7.0.0) lib/action_controller/metal/flash.rb:62:in `redirect_to' 
9actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:42:in `block in redirect_to' 
10activesupport (7.0.0) lib/active_support/notifications.rb:206:in `block in instrument' 
11activesupport (7.0.0) lib/active_support/notifications/instrumenter.rb:24:in `instrument' 
12activesupport (7.0.0) lib/active_support/notifications.rb:206:in `instrument' 
13actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:41:in `redirect_to' 
14responders (3.0.1) lib/action_controller/responder.rb:147:in `redirect_to' 
15responders (3.0.1) lib/action_controller/responder.rb:207:in `navigation_behavior' 
16responders (3.0.1) lib/action_controller/responder.rb:174:in `rescue in to_html' 
17responders (3.0.1) lib/action_controller/responder.rb:171:in `to_html' 
18responders (3.0.1) lib/action_controller/responder.rb:165:in `respond' 
19responders (3.0.1) lib/action_controller/responder.rb:158:in `call' 
20responders (3.0.1) lib/action_controller/respond_with.rb:213:in `respond_with' 
21devise (4.8.1) app/controllers/devise/registrations_controller.rb:25:in `create' 
22actionpack (7.0.0) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action' 
23actionpack (7.0.0) lib/abstract_controller/base.rb:214:in `process_action' 
24actionpack (7.0.0) lib/action_controller/metal/rendering.rb:53:in `process_action' 
25actionpack (7.0.0) lib/abstract_controller/callbacks.rb:234:in `block in process_action' 
26activesupport (7.0.0) lib/active_support/callbacks.rb:118:in `block in run_callbacks' 
27actiontext (7.0.0) lib/action_text/rendering.rb:20:in `with_renderer' 
28actiontext (7.0.0) lib/action_text/engine.rb:69:in `block (4 levels) in <class:Engine>' 
29activesupport (7.0.0) lib/active_support/callbacks.rb:127:in `instance_exec' 
30activesupport (7.0.0) lib/active_support/callbacks.rb:127:in `block in run_callbacks' 
31activesupport (7.0.0) lib/active_support/callbacks.rb:138:in `run_callbacks' 
32actionpack (7.0.0) lib/abstract_controller/callbacks.rb:233:in `process_action' 
33actionpack (7.0.0) lib/action_controller/metal/rescue.rb:22:in `process_action' 
34actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:67:in `block in process_action' 
35activesupport (7.0.0) lib/active_support/notifications.rb:206:in `block in instrument' 
36activesupport (7.0.0) lib/active_support/notifications/instrumenter.rb:24:in `instrument' 
37activesupport (7.0.0) lib/active_support/notifications.rb:206:in `instrument' 
38actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:66:in `process_action' 
39actionpack (7.0.0) lib/action_controller/metal/params_wrapper.rb:259:in `process_action' 
40activerecord (7.0.0) lib/active_record/railties/controller_runtime.rb:27:in `process_action' 
41actionpack (7.0.0) lib/abstract_controller/base.rb:151:in `process' 
42actionview (7.0.0) lib/action_view/rendering.rb:39:in `process' 
43actionpack (7.0.0) lib/action_controller/metal.rb:188:in `dispatch' 
44actionpack (7.0.0) lib/action_controller/metal.rb:251:in `dispatch' 
45actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:49:in `dispatch' 
46actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:32:in `serve' 
47actionpack (7.0.0) lib/action_dispatch/routing/mapper.rb:18:in `block in <class:Constraints>' 
48actionpack (7.0.0) lib/action_dispatch/routing/mapper.rb:48:in `serve' 
49actionpack (7.0.0) lib/action_dispatch/journey/router.rb:50:in `block in serve' 
50actionpack (7.0.0) lib/action_dispatch/journey/router.rb:32:in `each' 
51actionpack (7.0.0) lib/action_dispatch/journey/router.rb:32:in `serve' 
52actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:850:in `call' 
53warden (1.2.9) lib/warden/manager.rb:36:in `block in call' 
54warden (1.2.9) lib/warden/manager.rb:34:in `catch' 
55warden (1.2.9) lib/warden/manager.rb:34:in `call' 
56rack (2.2.3) lib/rack/tempfile_reaper.rb:15:in `call' 
57rack (2.2.3) lib/rack/etag.rb:27:in `call' 
58rack (2.2.3) lib/rack/conditional_get.rb:40:in `call' 
59rack (2.2.3) lib/rack/head.rb:12:in `call' 
60actionpack (7.0.0) lib/action_dispatch/http/permissions_policy.rb:22:in `call' 
61actionpack (7.0.0) lib/action_dispatch/http/content_security_policy.rb:18:in `call' 
62rack (2.2.3) lib/rack/session/abstract/id.rb:266:in `context' 
63rack (2.2.3) lib/rack/session/abstract/id.rb:260:in `call' 
64actionpack (7.0.0) lib/action_dispatch/middleware/cookies.rb:693:in `call' 
65activerecord (7.0.0) lib/active_record/migration.rb:603:in `call' 
66actionpack (7.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call' 
67activesupport (7.0.0) lib/active_support/callbacks.rb:99:in `run_callbacks' 
68actionpack (7.0.0) lib/action_dispatch/middleware/callbacks.rb:26:in `call' 
69actionpack (7.0.0) lib/action_dispatch/middleware/executor.rb:14:in `call' 
70actionpack (7.0.0) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call' 
71actionpack (7.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:28:in `call' 
72web-console (4.2.0) lib/web_console/middleware.rb:132:in `call_app' 
73web-console (4.2.0) lib/web_console/middleware.rb:28:in `block in call' 
74web-console (4.2.0) lib/web_console/middleware.rb:17:in `catch' 
75web-console (4.2.0) lib/web_console/middleware.rb:17:in `call' 
76actionpack (7.0.0) lib/action_dispatch/middleware/show_exceptions.rb:26:in `call' 
77railties (7.0.0) lib/rails/rack/logger.rb:36:in `call_app' 
78railties (7.0.0) lib/rails/rack/logger.rb:25:in `block in call' 
79activesupport (7.0.0) lib/active_support/tagged_logging.rb:99:in `block in tagged' 
80activesupport (7.0.0) lib/active_support/tagged_logging.rb:37:in `tagged' 
81activesupport (7.0.0) lib/active_support/tagged_logging.rb:99:in `tagged' 
82railties (7.0.0) lib/rails/rack/logger.rb:25:in `call' 
83sprockets-rails (3.4.2) lib/sprockets/rails/quiet_assets.rb:13:in `call' 
84actionpack (7.0.0) lib/action_dispatch/middleware/remote_ip.rb:93:in `call' 
85actionpack (7.0.0) lib/action_dispatch/middleware/request_id.rb:26:in `call' 
86rack (2.2.3) lib/rack/method_override.rb:24:in `call' 
87rack (2.2.3) lib/rack/runtime.rb:22:in `call' 
88activesupport (7.0.0) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call' 
89actionpack (7.0.0) lib/action_dispatch/middleware/server_timing.rb:20:in `call' 
90actionpack (7.0.0) lib/action_dispatch/middleware/executor.rb:14:in `call' 
91actionpack (7.0.0) lib/action_dispatch/middleware/static.rb:23:in `call' 
92rack (2.2.3) lib/rack/sendfile.rb:110:in `call' 
93actionpack (7.0.0) lib/action_dispatch/middleware/host_authorization.rb:137:in `call' 
94railties (7.0.0) lib/rails/engine.rb:530:in `call' 
95puma (5.5.2) lib/puma/configuration.rb:249:in `call' 
96puma (5.5.2) lib/puma/request.rb:77:in `block in handle_request' 
97puma (5.5.2) lib/puma/thread_pool.rb:340:in `with_force_shutdown' 
98puma (5.5.2) lib/puma/request.rb:76:in `handle_request' 
99puma (5.5.2) lib/puma/server.rb:447:in `process_client' 
100puma (5.5.2) lib/puma/thread_pool.rb:147:in `block in spawn_thread' 
101

My routes.rb:

1actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:231:in `public_send' 
2actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:231:in `polymorphic_method' 
3actionpack (7.0.0) lib/action_dispatch/routing/polymorphic_routes.rb:116:in `polymorphic_url' 
4actionpack (7.0.0) lib/action_dispatch/routing/url_for.rb:187:in `full_url_for' 
5actionpack (7.0.0) lib/action_dispatch/routing/url_for.rb:170:in `url_for' 
6actionpack (7.0.0) lib/action_controller/metal/redirecting.rb:144:in `_compute_redirect_to_location' 
7actionpack (7.0.0) lib/action_controller/metal/redirecting.rb:89:in `redirect_to' 
8actionpack (7.0.0) lib/action_controller/metal/flash.rb:62:in `redirect_to' 
9actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:42:in `block in redirect_to' 
10activesupport (7.0.0) lib/active_support/notifications.rb:206:in `block in instrument' 
11activesupport (7.0.0) lib/active_support/notifications/instrumenter.rb:24:in `instrument' 
12activesupport (7.0.0) lib/active_support/notifications.rb:206:in `instrument' 
13actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:41:in `redirect_to' 
14responders (3.0.1) lib/action_controller/responder.rb:147:in `redirect_to' 
15responders (3.0.1) lib/action_controller/responder.rb:207:in `navigation_behavior' 
16responders (3.0.1) lib/action_controller/responder.rb:174:in `rescue in to_html' 
17responders (3.0.1) lib/action_controller/responder.rb:171:in `to_html' 
18responders (3.0.1) lib/action_controller/responder.rb:165:in `respond' 
19responders (3.0.1) lib/action_controller/responder.rb:158:in `call' 
20responders (3.0.1) lib/action_controller/respond_with.rb:213:in `respond_with' 
21devise (4.8.1) app/controllers/devise/registrations_controller.rb:25:in `create' 
22actionpack (7.0.0) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action' 
23actionpack (7.0.0) lib/abstract_controller/base.rb:214:in `process_action' 
24actionpack (7.0.0) lib/action_controller/metal/rendering.rb:53:in `process_action' 
25actionpack (7.0.0) lib/abstract_controller/callbacks.rb:234:in `block in process_action' 
26activesupport (7.0.0) lib/active_support/callbacks.rb:118:in `block in run_callbacks' 
27actiontext (7.0.0) lib/action_text/rendering.rb:20:in `with_renderer' 
28actiontext (7.0.0) lib/action_text/engine.rb:69:in `block (4 levels) in <class:Engine>' 
29activesupport (7.0.0) lib/active_support/callbacks.rb:127:in `instance_exec' 
30activesupport (7.0.0) lib/active_support/callbacks.rb:127:in `block in run_callbacks' 
31activesupport (7.0.0) lib/active_support/callbacks.rb:138:in `run_callbacks' 
32actionpack (7.0.0) lib/abstract_controller/callbacks.rb:233:in `process_action' 
33actionpack (7.0.0) lib/action_controller/metal/rescue.rb:22:in `process_action' 
34actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:67:in `block in process_action' 
35activesupport (7.0.0) lib/active_support/notifications.rb:206:in `block in instrument' 
36activesupport (7.0.0) lib/active_support/notifications/instrumenter.rb:24:in `instrument' 
37activesupport (7.0.0) lib/active_support/notifications.rb:206:in `instrument' 
38actionpack (7.0.0) lib/action_controller/metal/instrumentation.rb:66:in `process_action' 
39actionpack (7.0.0) lib/action_controller/metal/params_wrapper.rb:259:in `process_action' 
40activerecord (7.0.0) lib/active_record/railties/controller_runtime.rb:27:in `process_action' 
41actionpack (7.0.0) lib/abstract_controller/base.rb:151:in `process' 
42actionview (7.0.0) lib/action_view/rendering.rb:39:in `process' 
43actionpack (7.0.0) lib/action_controller/metal.rb:188:in `dispatch' 
44actionpack (7.0.0) lib/action_controller/metal.rb:251:in `dispatch' 
45actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:49:in `dispatch' 
46actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:32:in `serve' 
47actionpack (7.0.0) lib/action_dispatch/routing/mapper.rb:18:in `block in <class:Constraints>' 
48actionpack (7.0.0) lib/action_dispatch/routing/mapper.rb:48:in `serve' 
49actionpack (7.0.0) lib/action_dispatch/journey/router.rb:50:in `block in serve' 
50actionpack (7.0.0) lib/action_dispatch/journey/router.rb:32:in `each' 
51actionpack (7.0.0) lib/action_dispatch/journey/router.rb:32:in `serve' 
52actionpack (7.0.0) lib/action_dispatch/routing/route_set.rb:850:in `call' 
53warden (1.2.9) lib/warden/manager.rb:36:in `block in call' 
54warden (1.2.9) lib/warden/manager.rb:34:in `catch' 
55warden (1.2.9) lib/warden/manager.rb:34:in `call' 
56rack (2.2.3) lib/rack/tempfile_reaper.rb:15:in `call' 
57rack (2.2.3) lib/rack/etag.rb:27:in `call' 
58rack (2.2.3) lib/rack/conditional_get.rb:40:in `call' 
59rack (2.2.3) lib/rack/head.rb:12:in `call' 
60actionpack (7.0.0) lib/action_dispatch/http/permissions_policy.rb:22:in `call' 
61actionpack (7.0.0) lib/action_dispatch/http/content_security_policy.rb:18:in `call' 
62rack (2.2.3) lib/rack/session/abstract/id.rb:266:in `context' 
63rack (2.2.3) lib/rack/session/abstract/id.rb:260:in `call' 
64actionpack (7.0.0) lib/action_dispatch/middleware/cookies.rb:693:in `call' 
65activerecord (7.0.0) lib/active_record/migration.rb:603:in `call' 
66actionpack (7.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call' 
67activesupport (7.0.0) lib/active_support/callbacks.rb:99:in `run_callbacks' 
68actionpack (7.0.0) lib/action_dispatch/middleware/callbacks.rb:26:in `call' 
69actionpack (7.0.0) lib/action_dispatch/middleware/executor.rb:14:in `call' 
70actionpack (7.0.0) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call' 
71actionpack (7.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:28:in `call' 
72web-console (4.2.0) lib/web_console/middleware.rb:132:in `call_app' 
73web-console (4.2.0) lib/web_console/middleware.rb:28:in `block in call' 
74web-console (4.2.0) lib/web_console/middleware.rb:17:in `catch' 
75web-console (4.2.0) lib/web_console/middleware.rb:17:in `call' 
76actionpack (7.0.0) lib/action_dispatch/middleware/show_exceptions.rb:26:in `call' 
77railties (7.0.0) lib/rails/rack/logger.rb:36:in `call_app' 
78railties (7.0.0) lib/rails/rack/logger.rb:25:in `block in call' 
79activesupport (7.0.0) lib/active_support/tagged_logging.rb:99:in `block in tagged' 
80activesupport (7.0.0) lib/active_support/tagged_logging.rb:37:in `tagged' 
81activesupport (7.0.0) lib/active_support/tagged_logging.rb:99:in `tagged' 
82railties (7.0.0) lib/rails/rack/logger.rb:25:in `call' 
83sprockets-rails (3.4.2) lib/sprockets/rails/quiet_assets.rb:13:in `call' 
84actionpack (7.0.0) lib/action_dispatch/middleware/remote_ip.rb:93:in `call' 
85actionpack (7.0.0) lib/action_dispatch/middleware/request_id.rb:26:in `call' 
86rack (2.2.3) lib/rack/method_override.rb:24:in `call' 
87rack (2.2.3) lib/rack/runtime.rb:22:in `call' 
88activesupport (7.0.0) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call' 
89actionpack (7.0.0) lib/action_dispatch/middleware/server_timing.rb:20:in `call' 
90actionpack (7.0.0) lib/action_dispatch/middleware/executor.rb:14:in `call' 
91actionpack (7.0.0) lib/action_dispatch/middleware/static.rb:23:in `call' 
92rack (2.2.3) lib/rack/sendfile.rb:110:in `call' 
93actionpack (7.0.0) lib/action_dispatch/middleware/host_authorization.rb:137:in `call' 
94railties (7.0.0) lib/rails/engine.rb:530:in `call' 
95puma (5.5.2) lib/puma/configuration.rb:249:in `call' 
96puma (5.5.2) lib/puma/request.rb:77:in `block in handle_request' 
97puma (5.5.2) lib/puma/thread_pool.rb:340:in `with_force_shutdown' 
98puma (5.5.2) lib/puma/request.rb:76:in `handle_request' 
99puma (5.5.2) lib/puma/server.rb:447:in `process_client' 
100puma (5.5.2) lib/puma/thread_pool.rb:147:in `block in spawn_thread' 
101Rails.application.routes.draw do
102  devise_for :users
103  resources :teachers
104  resources :offices
105  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
106
107  # Defines the root path route ("/")
108  root to: "offices#index"
109  # root "articles#index"
110end
111

ANSWER

Answered 2022-Jan-03 at 12:08

This seems to a be a known issue with Rails 7 and Devise now. To fix it in the meantime simply add the following line to your devise.rb.

config.navigational_formats = ['*/*', :html, :turbo_stream]

Source: https://github.com/heartcombo/devise/issues/5439

Source https://stackoverflow.com/questions/70413914

QUESTION

Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException

Asked 2022-Mar-03 at 15:46

I'm using Asp.Net Core Web Api 6

I'm facing an error when migrating my DbContext and when updating the database

The Error

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10

But it does not affect the Migration process and Update-Database

Therefore, My question is,

  • How to fix it
  • Is this going to affect the project later?

Program.cs

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10Log.Information("Application Is Starting");
11
12    var builder = WebApplication.CreateBuilder(args);
13
14    // Full setup of serilog. We read log settings from appsettings.json
15    builder.Host.UseSerilog((context, services, configuration) => configuration
16        .ReadFrom.Configuration(context.Configuration)
17        .ReadFrom.Services(services)
18        .Enrich.FromLogContext());
19
20
21    // Add services to the container.
22    builder.Services.AddDbContext<LocalDbContext>(options =>
23        options.UseSqlServer(builder.Configuration.GetConnectionString("localConnection"))
24    );
25
26    builder.Services.AddControllers();
27    builder.Services.AddCors(options =>
28    {
29        options.AddPolicy("AllowAll", builder =>
30            builder
31                .AllowAnyOrigin()
32                .AllowAnyMethod()
33                .AllowAnyHeader()
34            );
35    });
36    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
37    builder.Services.AddEndpointsApiExplorer();
38    builder.Services.AddSwaggerGen();
39
40    var app = builder.Build();
41
42    app.UseSerilogRequestLogging(configure =>
43    {
44        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
45    });
46
47    // Configure the HTTP request pipeline.
48    if (app.Environment.IsDevelopment())
49    {
50        app.UseSwagger();
51        app.UseSwaggerUI();
52    }
53
54    app.UseCors("AllowAll");
55
56    app.UseHttpsRedirection();
57
58    app.UseAuthorization();
59
60    app.MapControllers();
61
62    app.Run();
63

ANSWER

Answered 2022-Mar-03 at 15:46

Add try/catch similar to the above around IHostBulder.Build() in any .NET/EF Core 6.0 RC2 project, and attempt to add a migration can reproduce the issue.

We can fix the issue with the following :

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10Log.Information("Application Is Starting");
11
12    var builder = WebApplication.CreateBuilder(args);
13
14    // Full setup of serilog. We read log settings from appsettings.json
15    builder.Host.UseSerilog((context, services, configuration) => configuration
16        .ReadFrom.Configuration(context.Configuration)
17        .ReadFrom.Services(services)
18        .Enrich.FromLogContext());
19
20
21    // Add services to the container.
22    builder.Services.AddDbContext<LocalDbContext>(options =>
23        options.UseSqlServer(builder.Configuration.GetConnectionString("localConnection"))
24    );
25
26    builder.Services.AddControllers();
27    builder.Services.AddCors(options =>
28    {
29        options.AddPolicy("AllowAll", builder =>
30            builder
31                .AllowAnyOrigin()
32                .AllowAnyMethod()
33                .AllowAnyHeader()
34            );
35    });
36    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
37    builder.Services.AddEndpointsApiExplorer();
38    builder.Services.AddSwaggerGen();
39
40    var app = builder.Build();
41
42    app.UseSerilogRequestLogging(configure =>
43    {
44        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
45    });
46
47    // Configure the HTTP request pipeline.
48    if (app.Environment.IsDevelopment())
49    {
50        app.UseSwagger();
51        app.UseSwaggerUI();
52    }
53
54    app.UseCors("AllowAll");
55
56    app.UseHttpsRedirection();
57
58    app.UseAuthorization();
59
60    app.MapControllers();
61
62    app.Run();
63catch (Exception ex)
64{
65   string type = ex.GetType().Name;
66   if (type.Equals("StopTheHostException", StringComparison.Ordinal))
67   {
68      throw;
69   }
70
71   _logger.Fatal(ex, "Unhandled exception");
72   return 1;
73}
74

For more details on this issue, you can refer to this article.

StopTheHostException should be made public to be dealt with gracefully #60600

Source https://stackoverflow.com/questions/70247187

QUESTION

Lambda expressions and anonymous classes don't work when loaded as hidden classes

Asked 2022-Feb-26 at 05:14

I am trying to compile and load dynamically generated Java code during runtime. Since both ClassLoader::defineClass and Unsafe::defineAnonymousClass have serious drawbacks in this scenario, I tried using hidden classes via Lookup::defineHiddenClass instead. This works fine for all classes that I tried to load, except for those that call lambda expressions or contain anonymous classes.

Calling a lambda expression throws the following exception:

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8

Executing code that instantiates an anonymous class throws the following error:

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29

This is a short example that recreates the problem:

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50

I've already tried compiling and running the code with different JDKs, using different ways to create new instances of the hidden class, searching for bugs at https://bugs.openjdk.java.net/, messing with the bytecode itself and several other things. I am not an expert on Java internals, so I am not sure whether I have not understood the JEP that introduced hidden classes correctly.

Am I doing something wrong, is this just impossible or is this a bug?

Edit: The JEP states

Migration should take the following into account: To invoke private nestmate instance methods from code in a hidden class, use invokevirtual or invokeinterface instead of invokespecial. Generated bytecode that uses invokespecial to invoke a private nestmate instance method will fail verification. invokespecial should only be used to invoke private nestmate constructors.

This might be the problem for the anonymous class. Is there a way to compile the code such that invokespecial is avoided in the bytecode?

ANSWER

Answered 2022-Feb-23 at 18:19

You can not turn arbitrary classes into hidden classes.

The documentation of defineHiddenClass contains the sentence

  • On any attempt to resolve the entry in the run-time constant pool indicated by this_class, the symbolic reference is considered to be resolved to C and resolution always succeeds immediately.

What it doesn’t spell out explicitly is that this is the only place where a type resolution ever ends up at the hidden class.

But it has been said unambiguously in bug report JDK-8222730:

For a hidden class, its specified hidden name should only be accessible through the hidden class's 'this_class' constant pool entry.

The class should not be accessible by specifying its original name in, for example, a method or field signature even within the hidden class.

Which we can check. Even a simple case like

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71

will already fail. Note that it is a special case that the attempt to resolve the original class name LambdaRunner within the hidden class will not fail, as you used an existing class as template. So you get an IncompatibleClassChangeError or a VerifierError due to mismatches between the hidden class and the existing LambdaRunner class. When you don’t use a class definition of an existing class, you’d get a NoClassDefFoundError.

The same applies to

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80

As the cited bug report said, neither field nor methods can refer to the hidden class in their signature.

A less intuitive example is

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80    static class LambdaRunner implements Runnable {
81        @Override
82        public void run() {
83            System.out.println("" + this);
84        }
85    }
86

which will fail depending on the compiler and options, as when the StringConcatFactory is used, the behavior is like an invocation of a method having all non-constant parts as parameters and returning a String. So this is another case of having the hidden class in a method signature.


Lambda expressions are special, as a class like

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80    static class LambdaRunner implements Runnable {
81        @Override
82        public void run() {
83            System.out.println("" + this);
84        }
85    }
86    static class LambdaRunner implements Runnable {
87        @Override
88        public void run() {
89            Runnable runnable = () -> System.out.println("Success");
90            runnable.run();
91        }
92    }
93

gets compiled similar to

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80    static class LambdaRunner implements Runnable {
81        @Override
82        public void run() {
83            System.out.println("" + this);
84        }
85    }
86    static class LambdaRunner implements Runnable {
87        @Override
88        public void run() {
89            Runnable runnable = () -> System.out.println("Success");
90            runnable.run();
91        }
92    }
93    static class LambdaRunner implements Runnable {
94        @Override
95        public void run() {
96            Runnable runnable = LambdaRunner::lambdaBody;
97            runnable.run();
98        }
99        private static void lambdaBody() {
100            System.out.println("Success");
101        }
102    }
103

which doesn’t have the hidden class in the method signature, but has to refer to the method holding the body of the lambda expression as a MethodReference. Within the constant pool, the description of this method refers to its declaring class using the this_class entry. So it gets redirected to the hidden class as described in the documentation.

But the construction of the MethodType as part of the MethodReference does not use this information to load a Class like a class literal would do. Instead, it tries to load the hidden class through the defining class loader, which fails with the NoClassDefFoundError you have posted.

This seems to be related to JDK-8130087 which suggests that ordinary method resolution differs from the way, MethodType works, which can make MethodType fail where just invoking the method would work.

But it’s possible to demonstrate that even fixing this issue wouldn’t solve the general problem:

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80    static class LambdaRunner implements Runnable {
81        @Override
82        public void run() {
83            System.out.println("" + this);
84        }
85    }
86    static class LambdaRunner implements Runnable {
87        @Override
88        public void run() {
89            Runnable runnable = () -> System.out.println("Success");
90            runnable.run();
91        }
92    }
93    static class LambdaRunner implements Runnable {
94        @Override
95        public void run() {
96            Runnable runnable = LambdaRunner::lambdaBody;
97            runnable.run();
98        }
99        private static void lambdaBody() {
100            System.out.println("Success");
101        }
102    }
103    static class LambdaRunner implements Runnable {
104        @Override
105        public void run() {
106            var lookup = MethodHandles.lookup();
107            var noArgVoid = MethodType.methodType(void.class);
108            try {
109                MethodHandle mh = LambdaMetafactory.metafactory(lookup, "run",
110                    MethodType.methodType(Runnable.class), noArgVoid,
111                    lookup.findStatic(LambdaRunner.class, "lambdaBody", noArgVoid),
112                    noArgVoid).getTarget();
113                System.out.println("got factory");
114                Runnable runnable = (Runnable)mh.invokeExact();
115                System.out.println("got runnable");
116                runnable.run();
117            }
118            catch(RuntimeException|Error e) {
119                throw e;
120            }
121            catch(Throwable e) {
122                throw new AssertionError(e);
123            }
124        }
125        private static void lambdaBody() {
126            System.out.println("Success");
127        }
128    }
129

This bypasses the problem described above and calls the LambdaMetafactory manually. When being redefined as hidden class, it will print:

1Exception in thread "main" java.lang.NoClassDefFoundError: tests/HiddenClassLambdaTest$LambdaRunner/0x0000000800c04400
2    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:22)
3Caused by: java.lang.ClassNotFoundException: tests.HiddenClassLambdaTest$LambdaRunner.0x0000000800c04400
4    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
5    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
6    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
7    ... 1 more
8Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
9Exception Details:
10  Location:
11    tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400.run()V @5: invokespecial
12  Reason:
13    Type 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' (current frame, stack[2]) is not assignable to 'tests/HiddenClassLambdaTest$LambdaRunner'
14  Current Frame:
15    bci: @5
16    flags: { }
17    locals: { 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
18    stack: { uninitialized 0, uninitialized 0, 'tests/HiddenClassLambdaTest$LambdaRunner+0x0000000800c00400' }
19  Bytecode:
20    0000000: bb00 1159 2ab7 0013 4cb1               
21
22    at java.base/java.lang.ClassLoader.defineClass0(Native Method)
23    at java.base/java.lang.System$2.defineClass(System.java:2193)
24    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2446)
25    at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClassAsLookup(MethodHandles.java:2427)
26    at java.base/java.lang.invoke.MethodHandles$Lookup.defineHiddenClass(MethodHandles.java:2133)
27    at tests.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:25)
28
29import java.lang.invoke.MethodHandles;
30
31public class HiddenClassLambdaTest {
32    /** This class is to be loaded and executed as hidden class */
33    public static final class LambdaRunner implements Runnable {
34        @Override public void run() {
35            Runnable runnable = () -> System.out.println("Success");
36            runnable.run();
37        }
38    }
39    
40    public static void main(String[] args) throws Throwable {
41        // Path to the class file of the nested class defined above
42        String nestedClassPath = HiddenClassLambdaTest.class.getTypeName().replace('.','/') + "$LambdaRunner.class";
43        // Class file content of the LambdaRunner class
44        byte[] classFileContents = HiddenClassLambdaTest.class.getClassLoader().getResourceAsStream(nestedClassPath).readAllBytes();
45        Class<?> lambdaRunnerClass = MethodHandles.lookup().defineHiddenClass(classFileContents, true).lookupClass();
46        Runnable lambdaRunnerInstance = (Runnable) lambdaRunnerClass.getConstructor().newInstance();
47        lambdaRunnerInstance.run();
48    }
49}
50public class HiddenClassLambdaTest {
51
52    public static void main(String[] args) throws Throwable {
53        byte[] classFileContents = HiddenClassLambdaTest.class
54            .getResourceAsStream("HiddenClassLambdaTest$LambdaRunner.class")
55            .readAllBytes();
56        var hidden = MethodHandles.lookup()
57            .defineHiddenClass(classFileContents, true, ClassOption.NESTMATE);
58        Runnable lambdaRunnerInstance = (Runnable)hidden.findConstructor(
59            hidden.lookupClass(), MethodType.methodType(void.class)).invoke();
60        lambdaRunnerInstance.run();
61    }
62
63    static class LambdaRunner implements Runnable {
64        LambdaRunner field = this;
65
66        @Override
67        public void run() {
68        }
69    }
70}
71    static class LambdaRunner implements Runnable {
72        static void method(LambdaRunner arg) {
73        }
74
75        @Override
76        public void run() {
77            method(this);
78        }
79    }
80    static class LambdaRunner implements Runnable {
81        @Override
82        public void run() {
83            System.out.println("" + this);
84        }
85    }
86    static class LambdaRunner implements Runnable {
87        @Override
88        public void run() {
89            Runnable runnable = () -> System.out.println("Success");
90            runnable.run();
91        }
92    }
93    static class LambdaRunner implements Runnable {
94        @Override
95        public void run() {
96            Runnable runnable = LambdaRunner::lambdaBody;
97            runnable.run();
98        }
99        private static void lambdaBody() {
100            System.out.println("Success");
101        }
102    }
103    static class LambdaRunner implements Runnable {
104        @Override
105        public void run() {
106            var lookup = MethodHandles.lookup();
107            var noArgVoid = MethodType.methodType(void.class);
108            try {
109                MethodHandle mh = LambdaMetafactory.metafactory(lookup, "run",
110                    MethodType.methodType(Runnable.class), noArgVoid,
111                    lookup.findStatic(LambdaRunner.class, "lambdaBody", noArgVoid),
112                    noArgVoid).getTarget();
113                System.out.println("got factory");
114                Runnable runnable = (Runnable)mh.invokeExact();
115                System.out.println("got runnable");
116                runnable.run();
117            }
118            catch(RuntimeException|Error e) {
119                throw e;
120            }
121            catch(Throwable e) {
122                throw new AssertionError(e);
123            }
124        }
125        private static void lambdaBody() {
126            System.out.println("Success");
127        }
128    }
129got factory
130got runnable
131Exception in thread "main" java.lang.NoClassDefFoundError: test/HiddenClassLambdaTest$LambdaRunner/0x0000000800c01400
132    at test/test.HiddenClassLambdaTest.main(HiddenClassLambdaTest.java:15)
133Caused by: java.lang.ClassNotFoundException: test.HiddenClassLambdaTest$LambdaRunner.0x0000000800c01400
134    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
135    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
136    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
137    ... 1 more
138

which shows that all obstacles have been circumvented, but when it comes to the actual invocation from the generated Runnable to the method holding the lambda body, it will fail due to the fact that the target class is hidden. A JVM with eager resolution of symbolic references might fail earlier, i.e. the example might not print got runnable then.

Unlike the old JVM anonymous classes, there is no way to link to a hidden class, not even from another hidden class.


The bottom line is, as said at the beginning, you can not turn arbitrary classes into hidden classes. Lambda expressions are not the only feature not working with hidden classes. It’s not a good idea to try and get surprised. Hidden classes should only be used in conjunction with bytecode generators carefully using only features known to work.

Source https://stackoverflow.com/questions/71224833

QUESTION

"Cannot read properties of undefined (reading 'pathname')" when testing pages in the v6 React Router

Asked 2022-Feb-03 at 00:48

When testing components with <Link>s, for example in my answer to Recommended approach for route-based tests within routes of react-router, I often use the following pattern to get access to the current location for testing purposes:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10

This worked fine up to v5.3, but after upgrading to v6 I get:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20

This use-case isn't covered in the migration docs, v6 has no testing guides so far and, although the API reference does show that the history prop is no longer expected:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20interface RouterProps {
21  basename?: string;
22  children?: React.ReactNode;
23  location: Partial&lt;Location&gt; | string;
24  navigationType?: NavigationType;
25  navigator: Navigator;
26  static?: boolean;
27}
28

it's not clear what the v6 equivalent is; I tried switching to navigator={history} but still got the same error.

To reproduce, copy the following files into a new directory and run npm install then npm test:

package.json

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20interface RouterProps {
21  basename?: string;
22  children?: React.ReactNode;
23  location: Partial&lt;Location&gt; | string;
24  navigationType?: NavigationType;
25  navigator: Navigator;
26  static?: boolean;
27}
28{
29  &quot;name&quot;: &quot;router6-demo&quot;,
30  &quot;version&quot;: &quot;1.0.0&quot;,
31  &quot;description&quot;: &quot;&quot;,
32  &quot;main&quot;: &quot;index.js&quot;,
33  &quot;scripts&quot;: {
34    &quot;test&quot;: &quot;jest&quot;
35  },
36  &quot;jest&quot;: {
37    &quot;testEnvironment&quot;: &quot;jsdom&quot;
38  },
39  &quot;babel&quot;: {
40    &quot;presets&quot;: [
41      &quot;@babel/preset-react&quot;
42    ]
43  },
44  &quot;keywords&quot;: [],
45  &quot;author&quot;: &quot;&quot;,
46  &quot;license&quot;: &quot;ISC&quot;,
47  &quot;devDependencies&quot;: {
48    &quot;@babel/preset-react&quot;: &quot;^7.16.0&quot;,
49    &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;,
50    &quot;jest&quot;: &quot;^27.3.1&quot;,
51    &quot;react&quot;: &quot;^17.0.2&quot;,
52    &quot;react-dom&quot;: &quot;^17.0.2&quot;,
53    &quot;react-router-dom&quot;: &quot;^6.0.0&quot;
54  }
55}
56
57

index.test.js:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20interface RouterProps {
21  basename?: string;
22  children?: React.ReactNode;
23  location: Partial&lt;Location&gt; | string;
24  navigationType?: NavigationType;
25  navigator: Navigator;
26  static?: boolean;
27}
28{
29  &quot;name&quot;: &quot;router6-demo&quot;,
30  &quot;version&quot;: &quot;1.0.0&quot;,
31  &quot;description&quot;: &quot;&quot;,
32  &quot;main&quot;: &quot;index.js&quot;,
33  &quot;scripts&quot;: {
34    &quot;test&quot;: &quot;jest&quot;
35  },
36  &quot;jest&quot;: {
37    &quot;testEnvironment&quot;: &quot;jsdom&quot;
38  },
39  &quot;babel&quot;: {
40    &quot;presets&quot;: [
41      &quot;@babel/preset-react&quot;
42    ]
43  },
44  &quot;keywords&quot;: [],
45  &quot;author&quot;: &quot;&quot;,
46  &quot;license&quot;: &quot;ISC&quot;,
47  &quot;devDependencies&quot;: {
48    &quot;@babel/preset-react&quot;: &quot;^7.16.0&quot;,
49    &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;,
50    &quot;jest&quot;: &quot;^27.3.1&quot;,
51    &quot;react&quot;: &quot;^17.0.2&quot;,
52    &quot;react-dom&quot;: &quot;^17.0.2&quot;,
53    &quot;react-router-dom&quot;: &quot;^6.0.0&quot;
54  }
55}
56
57const { render } = require(&quot;@testing-library/react&quot;);
58const { createMemoryHistory } = require(&quot;history&quot;);
59const React = require(&quot;react&quot;);
60const { Router } = require(&quot;react-router-dom&quot;);
61
62it(&quot;used to work&quot;, () =&gt; {
63  render(
64    &lt;Router history={createMemoryHistory()}&gt;&lt;/Router&gt;
65  );
66});
67

If you npm install --save-dev react-router@5 and run npm test again, you can see that this passes in v5.

ANSWER

Answered 2021-Nov-06 at 10:28

React Router v6 splits apart the history into multiple pieces, for this use case the relevant parts are the navigator and the location. This change is hinted at in Use useNavigate instead of useHistory, and you can see it in the definition of the Navigator type used in the Router props:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20interface RouterProps {
21  basename?: string;
22  children?: React.ReactNode;
23  location: Partial&lt;Location&gt; | string;
24  navigationType?: NavigationType;
25  navigator: Navigator;
26  static?: boolean;
27}
28{
29  &quot;name&quot;: &quot;router6-demo&quot;,
30  &quot;version&quot;: &quot;1.0.0&quot;,
31  &quot;description&quot;: &quot;&quot;,
32  &quot;main&quot;: &quot;index.js&quot;,
33  &quot;scripts&quot;: {
34    &quot;test&quot;: &quot;jest&quot;
35  },
36  &quot;jest&quot;: {
37    &quot;testEnvironment&quot;: &quot;jsdom&quot;
38  },
39  &quot;babel&quot;: {
40    &quot;presets&quot;: [
41      &quot;@babel/preset-react&quot;
42    ]
43  },
44  &quot;keywords&quot;: [],
45  &quot;author&quot;: &quot;&quot;,
46  &quot;license&quot;: &quot;ISC&quot;,
47  &quot;devDependencies&quot;: {
48    &quot;@babel/preset-react&quot;: &quot;^7.16.0&quot;,
49    &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;,
50    &quot;jest&quot;: &quot;^27.3.1&quot;,
51    &quot;react&quot;: &quot;^17.0.2&quot;,
52    &quot;react-dom&quot;: &quot;^17.0.2&quot;,
53    &quot;react-router-dom&quot;: &quot;^6.0.0&quot;
54  }
55}
56
57const { render } = require(&quot;@testing-library/react&quot;);
58const { createMemoryHistory } = require(&quot;history&quot;);
59const React = require(&quot;react&quot;);
60const { Router } = require(&quot;react-router-dom&quot;);
61
62it(&quot;used to work&quot;, () =&gt; {
63  render(
64    &lt;Router history={createMemoryHistory()}&gt;&lt;/Router&gt;
65  );
66});
67export declare type Navigator = Omit&lt;History, &quot;action&quot; | &quot;location&quot; | &quot;back&quot; | &quot;forward&quot; | &quot;listen&quot; | &quot;block&quot;&gt;;
68

Just changing history={history} to navigator={history} still left the location prop, from which the router was trying to access the pathname (among other properties), undefined. To get the test working again, update the rendering as follows:

1const renderInRouter = () =&gt; {
2  const history = createMemoryHistory();
3  const wrapper = render(
4    &lt;Router history={history}&gt;
5      &lt;MyPage /&gt;
6    &lt;/Router&gt;
7  );
8  return { ...wrapper, history };
9}
10 FAIL  ./demo.test.js
11  ✕ works (205 ms)
12
13  ● works
14
15    TypeError: Cannot read properties of undefined (reading 'pathname')
16
17      at Router (../packages/react-router/index.tsx:281:5)
18
19      ...
20interface RouterProps {
21  basename?: string;
22  children?: React.ReactNode;
23  location: Partial&lt;Location&gt; | string;
24  navigationType?: NavigationType;
25  navigator: Navigator;
26  static?: boolean;
27}
28{
29  &quot;name&quot;: &quot;router6-demo&quot;,
30  &quot;version&quot;: &quot;1.0.0&quot;,
31  &quot;description&quot;: &quot;&quot;,
32  &quot;main&quot;: &quot;index.js&quot;,
33  &quot;scripts&quot;: {
34    &quot;test&quot;: &quot;jest&quot;
35  },
36  &quot;jest&quot;: {
37    &quot;testEnvironment&quot;: &quot;jsdom&quot;
38  },
39  &quot;babel&quot;: {
40    &quot;presets&quot;: [
41      &quot;@babel/preset-react&quot;
42    ]
43  },
44  &quot;keywords&quot;: [],
45  &quot;author&quot;: &quot;&quot;,
46  &quot;license&quot;: &quot;ISC&quot;,
47  &quot;devDependencies&quot;: {
48    &quot;@babel/preset-react&quot;: &quot;^7.16.0&quot;,
49    &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;,
50    &quot;jest&quot;: &quot;^27.3.1&quot;,
51    &quot;react&quot;: &quot;^17.0.2&quot;,
52    &quot;react-dom&quot;: &quot;^17.0.2&quot;,
53    &quot;react-router-dom&quot;: &quot;^6.0.0&quot;
54  }
55}
56
57const { render } = require(&quot;@testing-library/react&quot;);
58const { createMemoryHistory } = require(&quot;history&quot;);
59const React = require(&quot;react&quot;);
60const { Router } = require(&quot;react-router-dom&quot;);
61
62it(&quot;used to work&quot;, () =&gt; {
63  render(
64    &lt;Router history={createMemoryHistory()}&gt;&lt;/Router&gt;
65  );
66});
67export declare type Navigator = Omit&lt;History, &quot;action&quot; | &quot;location&quot; | &quot;back&quot; | &quot;forward&quot; | &quot;listen&quot; | &quot;block&quot;&gt;;
68const { render } = require(&quot;@testing-library/react&quot;);
69const { createMemoryHistory } = require(&quot;history&quot;);
70const React = require(&quot;react&quot;);
71const { Router } = require(&quot;react-router-dom&quot;);
72
73it(&quot;works&quot;, () =&gt; {
74  const history = createMemoryHistory();
75  render(
76    &lt;Router location={history.location} navigator={history}&gt;&lt;/Router&gt;
77  );
78});
79

Source https://stackoverflow.com/questions/69859509

QUESTION

pymongo [SSL: CERTIFICATE_VERIFY_FAILED]: certificate has expired on Mongo Atlas

Asked 2022-Jan-29 at 22:03

I am using MongoDB(Mongo Atlas) in my Django app. All was working fine till yesterday. But today, when I ran the server, it is showing me the following error on console

1Exception in thread django-main-thread:
2Traceback (most recent call last):
3  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 973, in _bootstrap_inner
4    self.run()
5  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 910, in run
6    self._target(*self._args, **self._kwargs)
7  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\utils\autoreload.py&quot;, line 64, in wrapper
8    fn(*args, **kwargs)
9  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\commands\runserver.py&quot;, line 121, in inner_run
10    self.check_migrations()
11  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\base.py&quot;, line 486, in check_migrations
12    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
13  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\executor.py&quot;, line 18, in __init__
14    self.loader = MigrationLoader(self.connection)
15  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 53, in __init__
16    self.build_graph()
17  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 220, in build_graph
18    self.applied_migrations = recorder.applied_migrations()
19  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 77, in applied_migrations
20    if self.has_table():
21  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 56, in has_table
22    tables = self.connection.introspection.table_names(cursor)
23  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 52, in table_names
24    return get_names(cursor)
25  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 47, in get_names
26    return sorted(ti.name for ti in self.get_table_list(cursor)
27  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\djongo\introspection.py&quot;, line 47, in get_table_list
28    for c in cursor.db_conn.list_collection_names()
29  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 880, in list_collection_names
30    for result in self.list_collections(session=session, **kwargs)]
31  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 842, in list_collections
32    return self.__client._retryable_read(
33  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1514, in _retryable_read
34    server = self._select_server(
35  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1346, in _select_server
36    server = topology.select_server(server_selector)
37  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 244, in select_server
38    return random.choice(self.select_servers(selector,
39  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 202, in select_servers
40    server_descriptions = self._select_servers_loop(
41  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 218, in _select_servers_loop
42    raise ServerSelectionTimeoutError(
43pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129), Timeout: 30s, Topology Description: &lt;TopologyDescription id: 6155f0c9148b07ff5851a1b3, topology_type: ReplicaSetNoPrimary, servers: [&lt;ServerDescription ('cluster0-shard-00-00.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-01.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-02.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;]&gt;
44

I am using djongo as the database engine

1Exception in thread django-main-thread:
2Traceback (most recent call last):
3  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 973, in _bootstrap_inner
4    self.run()
5  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 910, in run
6    self._target(*self._args, **self._kwargs)
7  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\utils\autoreload.py&quot;, line 64, in wrapper
8    fn(*args, **kwargs)
9  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\commands\runserver.py&quot;, line 121, in inner_run
10    self.check_migrations()
11  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\base.py&quot;, line 486, in check_migrations
12    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
13  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\executor.py&quot;, line 18, in __init__
14    self.loader = MigrationLoader(self.connection)
15  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 53, in __init__
16    self.build_graph()
17  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 220, in build_graph
18    self.applied_migrations = recorder.applied_migrations()
19  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 77, in applied_migrations
20    if self.has_table():
21  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 56, in has_table
22    tables = self.connection.introspection.table_names(cursor)
23  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 52, in table_names
24    return get_names(cursor)
25  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 47, in get_names
26    return sorted(ti.name for ti in self.get_table_list(cursor)
27  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\djongo\introspection.py&quot;, line 47, in get_table_list
28    for c in cursor.db_conn.list_collection_names()
29  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 880, in list_collection_names
30    for result in self.list_collections(session=session, **kwargs)]
31  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 842, in list_collections
32    return self.__client._retryable_read(
33  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1514, in _retryable_read
34    server = self._select_server(
35  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1346, in _select_server
36    server = topology.select_server(server_selector)
37  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 244, in select_server
38    return random.choice(self.select_servers(selector,
39  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 202, in select_servers
40    server_descriptions = self._select_servers_loop(
41  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 218, in _select_servers_loop
42    raise ServerSelectionTimeoutError(
43pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129), Timeout: 30s, Topology Description: &lt;TopologyDescription id: 6155f0c9148b07ff5851a1b3, topology_type: ReplicaSetNoPrimary, servers: [&lt;ServerDescription ('cluster0-shard-00-00.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-01.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-02.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;]&gt;
44DATABASES = {
45    'default': {
46            'ENGINE': 'djongo',
47            'NAME': 'DbName',
48            'ENFORCE_SCHEMA': False,
49            'CLIENT': {
50                'host': 'mongodb+srv://username:password@cluster0.mny7y.mongodb.net/DbName?retryWrites=true&amp;w=majority'
51            }  
52    }
53}
54

And following dependencies are being used in the app

1Exception in thread django-main-thread:
2Traceback (most recent call last):
3  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 973, in _bootstrap_inner
4    self.run()
5  File &quot;c:\users\admin\appdata\local\programs\python\python39\lib\threading.py&quot;, line 910, in run
6    self._target(*self._args, **self._kwargs)
7  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\utils\autoreload.py&quot;, line 64, in wrapper
8    fn(*args, **kwargs)
9  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\commands\runserver.py&quot;, line 121, in inner_run
10    self.check_migrations()
11  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\base.py&quot;, line 486, in check_migrations
12    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
13  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\executor.py&quot;, line 18, in __init__
14    self.loader = MigrationLoader(self.connection)
15  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 53, in __init__
16    self.build_graph()
17  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py&quot;, line 220, in build_graph
18    self.applied_migrations = recorder.applied_migrations()
19  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 77, in applied_migrations
20    if self.has_table():
21  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py&quot;, line 56, in has_table
22    tables = self.connection.introspection.table_names(cursor)
23  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 52, in table_names
24    return get_names(cursor)
25  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py&quot;, line 47, in get_names
26    return sorted(ti.name for ti in self.get_table_list(cursor)
27  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\djongo\introspection.py&quot;, line 47, in get_table_list
28    for c in cursor.db_conn.list_collection_names()
29  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 880, in list_collection_names
30    for result in self.list_collections(session=session, **kwargs)]
31  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py&quot;, line 842, in list_collections
32    return self.__client._retryable_read(
33  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1514, in _retryable_read
34    server = self._select_server(
35  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py&quot;, line 1346, in _select_server
36    server = topology.select_server(server_selector)
37  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 244, in select_server
38    return random.choice(self.select_servers(selector,
39  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 202, in select_servers
40    server_descriptions = self._select_servers_loop(
41  File &quot;C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py&quot;, line 218, in _select_servers_loop
42    raise ServerSelectionTimeoutError(
43pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129), Timeout: 30s, Topology Description: &lt;TopologyDescription id: 6155f0c9148b07ff5851a1b3, topology_type: ReplicaSetNoPrimary, servers: [&lt;ServerDescription ('cluster0-shard-00-00.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-01.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;, &lt;ServerDescription ('cluster0-shard-00-02.mny7y.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.mny7y.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')&gt;]&gt;
44DATABASES = {
45    'default': {
46            'ENGINE': 'djongo',
47            'NAME': 'DbName',
48            'ENFORCE_SCHEMA': False,
49            'CLIENT': {
50                'host': 'mongodb+srv://username:password@cluster0.mny7y.mongodb.net/DbName?retryWrites=true&amp;w=majority'
51            }  
52    }
53}
54dj-database-url==0.5.0
55Django==3.2.5
56djangorestframework==3.12.4
57django-cors-headers==3.7.0
58gunicorn==20.1.0
59psycopg2==2.9.1
60pytz==2021.1
61whitenoise==5.3.0
62djongo==1.3.6
63dnspython==2.1.0
64

What should be done in order to resolve this error?

ANSWER

Answered 2021-Oct-03 at 05:57

This is because of a root CA Let’s Encrypt uses (and Mongo Atals uses Let's Encrypt) has expired on 2020-09-30 - namely the "IdentTrust DST Root CA X3" one.

The fix is to manually install in the Windows certificate store the "ISRG Root X1" and "ISRG Root X2" root certificates, and the "Let’s Encrypt R3" intermediate one - link to their official site - https://letsencrypt.org/certificates/

Copy from the comments: download the .der field from the 1st category, download, double click and follow the wizard to install it.

Source https://stackoverflow.com/questions/69397039

QUESTION

How to log production database changes made via the Django shell

Asked 2022-Jan-27 at 17:42

I would like to automatically generate some sort of log of all the database changes that are made via the Django shell in the production environment.

We use schema and data migration scripts to alter the production database and they are version controlled. Therefore if we introduce a bug, it's easy to track it back. But if a developer in the team changes the database via the Django shell which then introduces an issue, at the moment we can only hope that they remember what they did or/and we can find their commands in the Python shell history.

Example. Let's imagine that the following code was executed by a developer in the team via the Python shell:

1&gt;&gt;&gt; tm = TeamMembership.objects.get(person=alice)
2&gt;&gt;&gt; tm.end_date = date(2022,1,1)
3&gt;&gt;&gt; tm.save()
4

It changes a team membership object in the database. I would like to log this somehow.

I'm aware that there are a bunch of Django packages related to audit logging, but I'm only interested in the changes that are triggered from the Django shell, and I want to log the Python code that updated the data.

So the questions I have in mind:

  • I can log the statements from IPython but how do I know which one touched the database?
  • I can listen to the pre_save signal for all model to know if data changes, but how do I know if the source was from the Python shell? How do I know what was the original Python statement?

ANSWER

Answered 2022-Jan-19 at 09:20

You could use django's receiver annotation.

For example, if you want to detect any call of the save method, you could do:

1&gt;&gt;&gt; tm = TeamMembership.objects.get(person=alice)
2&gt;&gt;&gt; tm.end_date = date(2022,1,1)
3&gt;&gt;&gt; tm.save()
4from django.db.models.signals import post_save
5from django.dispatch import receiver
6import logging
7
8@receiver(post_save)
9def logg_save(sender, instance, **kwargs):
10    logging.debug(&quot;whatever you want to log&quot;)
11

Source https://stackoverflow.com/questions/70658151

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Migration

Tutorials and Learning Resources are not available at this moment for Migration

Share this Page

share link

Get latest updates on Migration